forked from goharbor/harbor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
systeminfo.go
268 lines (248 loc) · 8.57 KB
/
systeminfo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
// Copyright 2018 Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"errors"
"io/ioutil"
"net/http"
"os"
"strings"
"sync"
"fmt"
"github.com/goharbor/harbor/src/common"
"github.com/goharbor/harbor/src/common/dao"
clairdao "github.com/goharbor/harbor/src/common/dao/clair"
"github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/common/utils"
"github.com/goharbor/harbor/src/common/utils/clair"
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/core/config"
"github.com/goharbor/harbor/src/core/systeminfo"
"github.com/goharbor/harbor/src/core/systeminfo/imagestorage"
)
// SystemInfoAPI handle requests for getting system info /api/systeminfo
type SystemInfoAPI struct {
BaseController
}
const defaultRootCert = "/etc/core/ca/ca.crt"
const harborVersionFile = "/harbor/UIVERSION"
// SystemInfo models for system info.
type SystemInfo struct {
HarborStorage Storage `json:"storage"`
}
// Storage models for storage.
type Storage struct {
Total uint64 `json:"total"`
Free uint64 `json:"free"`
}
// namespaces stores all name spaces on Clair, it should be initialised only once.
type clairNamespaces struct {
sync.RWMutex
l []string
clair *clair.Client
}
func (n *clairNamespaces) get() ([]string, error) {
n.Lock()
defer n.Unlock()
if len(n.l) == 0 {
m := make(map[string]struct{})
if n.clair == nil {
n.clair = clair.NewClient(config.ClairEndpoint(), nil)
}
list, err := n.clair.ListNamespaces()
if err != nil {
return n.l, err
}
for _, n := range list {
ns := strings.Split(n, ":")[0]
m[ns] = struct{}{}
}
for k := range m {
n.l = append(n.l, k)
}
}
return n.l, nil
}
var (
namespaces = &clairNamespaces{}
)
// GeneralInfo wraps common systeminfo for anonymous request
type GeneralInfo struct {
WithNotary bool `json:"with_notary"`
WithClair bool `json:"with_clair"`
WithAdmiral bool `json:"with_admiral"`
AdmiralEndpoint string `json:"admiral_endpoint"`
AuthMode string `json:"auth_mode"`
AuthProxySettings *models.HTTPAuthProxy `json:"authproxy_settings,omitempty"`
RegistryURL string `json:"registry_url"`
ExtURL string `json:"external_url"`
ProjectCreationRestrict string `json:"project_creation_restriction"`
SelfRegistration bool `json:"self_registration"`
HasCARoot bool `json:"has_ca_root"`
HarborVersion string `json:"harbor_version"`
ClairVulnStatus *models.ClairVulnerabilityStatus `json:"clair_vulnerability_status,omitempty"`
RegistryStorageProviderName string `json:"registry_storage_provider_name"`
ReadOnly bool `json:"read_only"`
WithChartMuseum bool `json:"with_chartmuseum"`
}
// GetVolumeInfo gets specific volume storage info.
func (sia *SystemInfoAPI) GetVolumeInfo() {
if !sia.SecurityCtx.IsAuthenticated() {
sia.SendUnAuthorizedError(errors.New("UnAuthorized"))
return
}
if !sia.SecurityCtx.IsSysAdmin() {
sia.SendForbiddenError(errors.New(sia.SecurityCtx.GetUsername()))
return
}
systeminfo.Init()
capacity, err := imagestorage.GlobalDriver.Cap()
if err != nil {
log.Errorf("failed to get capacity: %v", err)
sia.SendInternalServerError(fmt.Errorf("failed to get capacity: %v", err))
return
}
systemInfo := SystemInfo{
HarborStorage: Storage{
Total: capacity.Total,
Free: capacity.Free,
},
}
sia.Data["json"] = systemInfo
sia.ServeJSON()
}
// GetCert gets default self-signed certificate.
func (sia *SystemInfoAPI) GetCert() {
if _, err := os.Stat(defaultRootCert); err == nil {
sia.Ctx.Output.Header("Content-Type", "application/octet-stream")
sia.Ctx.Output.Header("Content-Disposition", "attachment; filename=ca.crt")
http.ServeFile(sia.Ctx.ResponseWriter, sia.Ctx.Request, defaultRootCert)
} else if os.IsNotExist(err) {
log.Error("No certificate found.")
sia.SendNotFoundError(errors.New("no certificate found"))
return
} else {
log.Errorf("Unexpected error: %v", err)
sia.SendInternalServerError(fmt.Errorf("Unexpected error: %v", err))
return
}
}
// GetGeneralInfo returns the general system info, which is to be called by anonymous user
func (sia *SystemInfoAPI) GetGeneralInfo() {
cfg, err := config.GetSystemCfg()
if err != nil {
log.Errorf("Error occurred getting config: %v", err)
sia.SendInternalServerError(fmt.Errorf("Unexpected error: %v", err))
return
}
extURL := cfg[common.ExtEndpoint].(string)
var registryURL string
if l := strings.Split(extURL, "://"); len(l) > 1 {
registryURL = l[1]
} else {
registryURL = l[0]
}
_, caStatErr := os.Stat(defaultRootCert)
enableCADownload := caStatErr == nil && strings.HasPrefix(extURL, "https://")
harborVersion := sia.getVersion()
info := GeneralInfo{
AdmiralEndpoint: utils.SafeCastString(cfg[common.AdmiralEndpoint]),
WithAdmiral: config.WithAdmiral(),
WithNotary: config.WithNotary(),
WithClair: config.WithClair(),
AuthMode: utils.SafeCastString(cfg[common.AUTHMode]),
ProjectCreationRestrict: utils.SafeCastString(cfg[common.ProjectCreationRestriction]),
SelfRegistration: utils.SafeCastBool(cfg[common.SelfRegistration]),
ExtURL: extURL,
RegistryURL: registryURL,
HasCARoot: enableCADownload,
HarborVersion: harborVersion,
RegistryStorageProviderName: utils.SafeCastString(cfg[common.RegistryStorageProviderName]),
ReadOnly: config.ReadOnly(),
WithChartMuseum: config.WithChartMuseum(),
}
if info.WithClair {
info.ClairVulnStatus = getClairVulnStatus()
}
if info.AuthMode == common.HTTPAuth {
if s, err := config.HTTPAuthProxySetting(); err == nil {
info.AuthProxySettings = s
} else {
log.Warningf("Failed to get auth proxy setting, error: %v", err)
}
}
sia.Data["json"] = info
sia.ServeJSON()
}
// getVersion gets harbor version.
func (sia *SystemInfoAPI) getVersion() string {
version, err := ioutil.ReadFile(harborVersionFile)
if err != nil {
log.Errorf("Error occurred getting harbor version: %v", err)
return ""
}
return string(version[:])
}
func getClairVulnStatus() *models.ClairVulnerabilityStatus {
res := &models.ClairVulnerabilityStatus{}
last, err := clairdao.GetLastUpdate()
if err != nil {
log.Errorf("Failed to get last update from Clair DB, error: %v", err)
res.OverallUTC = 0
} else {
res.OverallUTC = last
log.Debugf("Clair vuln DB last update: %d", last)
}
details := []models.ClairNamespaceTimestamp{}
if res.OverallUTC > 0 {
l, err := dao.ListClairVulnTimestamps()
if err != nil {
log.Errorf("Failed to list Clair vulnerability timestamps, error:%v", err)
return res
}
m := make(map[string]int64)
for _, e := range l {
ns := strings.Split(e.Namespace, ":")
// only returns the latest time of one distro, i.e. unbuntu:14.04 and ubuntu:15.4 shares one timestamp
el := e.LastUpdate.UTC().Unix()
if ts, ok := m[ns[0]]; !ok || ts < el {
m[ns[0]] = el
}
}
list, err := namespaces.get()
if err != nil {
log.Errorf("Failed to get namespace list from Clair, error: %v", err)
}
// For namespaces not reported by notifier, the timestamp will be the overall db timestamp.
for _, n := range list {
if _, ok := m[n]; !ok {
m[n] = res.OverallUTC
}
}
for k, v := range m {
e := models.ClairNamespaceTimestamp{
Namespace: k,
Timestamp: v,
}
details = append(details, e)
}
}
res.Details = details
return res
}
// Ping ping the harbor core service.
func (sia *SystemInfoAPI) Ping() {
sia.Data["json"] = "Pong"
sia.ServeJSON()
}