-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
529 lines (466 loc) · 14.9 KB
/
config.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// 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 config
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"github.com/vmware/harbor/src/adminserver/client"
"github.com/vmware/harbor/src/common"
comcfg "github.com/vmware/harbor/src/common/config"
"github.com/vmware/harbor/src/common/models"
"github.com/vmware/harbor/src/common/secret"
"github.com/vmware/harbor/src/common/utils/log"
"github.com/vmware/harbor/src/ui/promgr"
"github.com/vmware/harbor/src/ui/promgr/pmsdriver"
"github.com/vmware/harbor/src/ui/promgr/pmsdriver/admiral"
"github.com/vmware/harbor/src/ui/promgr/pmsdriver/local"
)
const (
defaultKeyPath string = "/etc/ui/key"
defaultTokenFilePath string = "/etc/ui/token/tokens.properties"
)
var (
// SecretStore manages secrets
SecretStore *secret.Store
// AdminserverClient is a client for adminserver
AdminserverClient client.Client
// GlobalProjectMgr is initialized based on the deploy mode
GlobalProjectMgr promgr.ProjectManager
mg *comcfg.Manager
keyProvider comcfg.KeyProvider
// AdmiralClient is initialized only under integration deploy mode
// and can be passed to project manager as a parameter
AdmiralClient *http.Client
// TokenReader is used in integration mode to read token
TokenReader admiral.TokenReader
defaultCACertPath = "/etc/ui/ca/ca.crt"
)
// Init configurations
func Init() error {
//init key provider
initKeyProvider()
adminServerURL := os.Getenv("ADMINSERVER_URL")
if len(adminServerURL) == 0 {
adminServerURL = common.DefaultAdminserverEndpoint
}
return InitByURL(adminServerURL)
}
// InitByURL Init configurations with given url
func InitByURL(adminServerURL string) error {
log.Infof("initializing client for adminserver %s ...", adminServerURL)
cfg := &client.Config{
Secret: UISecret(),
}
AdminserverClient = client.NewClient(adminServerURL, cfg)
if err := AdminserverClient.Ping(); err != nil {
return fmt.Errorf("failed to ping adminserver: %v", err)
}
mg = comcfg.NewManager(AdminserverClient, true)
if err := Load(); err != nil {
return err
}
// init secret store
initSecretStore()
// init project manager based on deploy mode
if err := initProjectManager(); err != nil {
log.Errorf("Failed to initialise project manager, error: %v", err)
return err
}
return nil
}
func initKeyProvider() {
path := os.Getenv("KEY_PATH")
if len(path) == 0 {
path = defaultKeyPath
}
log.Infof("key path: %s", path)
keyProvider = comcfg.NewFileKeyProvider(path)
}
func initSecretStore() {
m := map[string]string{}
m[JobserviceSecret()] = secret.JobserviceUser
SecretStore = secret.NewStore(m)
}
func initProjectManager() error {
var driver pmsdriver.PMSDriver
if WithAdmiral() {
log.Debugf("Initialising Admiral client with certificate: %s", defaultCACertPath)
content, err := ioutil.ReadFile(defaultCACertPath)
if err != nil {
return err
}
pool := x509.NewCertPool()
if ok := pool.AppendCertsFromPEM(content); !ok {
return fmt.Errorf("failed to append cert content into cert pool")
}
AdmiralClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: pool,
},
},
}
// integration with admiral
log.Info("initializing the project manager based on PMS...")
path := os.Getenv("SERVICE_TOKEN_FILE_PATH")
if len(path) == 0 {
path = defaultTokenFilePath
}
log.Infof("service token file path: %s", path)
TokenReader = &admiral.FileTokenReader{
Path: path,
}
driver = admiral.NewDriver(AdmiralClient, AdmiralEndpoint(), TokenReader)
} else {
// standalone
log.Info("initializing the project manager based on local database...")
driver = local.NewDriver()
}
GlobalProjectMgr = promgr.NewDefaultProjectManager(driver, true)
return nil
}
// Load configurations
func Load() error {
_, err := mg.Load()
return err
}
// Reset configurations
func Reset() error {
return mg.Reset()
}
// Upload uploads all system configurations to admin server
func Upload(cfg map[string]interface{}) error {
return mg.Upload(cfg)
}
// GetSystemCfg returns the system configurations
func GetSystemCfg() (map[string]interface{}, error) {
return mg.Load()
}
// AuthMode ...
func AuthMode() (string, error) {
cfg, err := mg.Get()
if err != nil {
return "", err
}
return cfg[common.AUTHMode].(string), nil
}
// LDAPConf returns the setting of ldap server
func LDAPConf() (*models.LdapConf, error) {
cfg, err := mg.Get()
if err != nil {
return nil, err
}
ldapConf := &models.LdapConf{}
ldapConf.LdapURL = cfg[common.LDAPURL].(string)
ldapConf.LdapSearchDn = cfg[common.LDAPSearchDN].(string)
ldapConf.LdapSearchPassword = cfg[common.LDAPSearchPwd].(string)
ldapConf.LdapBaseDn = cfg[common.LDAPBaseDN].(string)
ldapConf.LdapUID = cfg[common.LDAPUID].(string)
ldapConf.LdapFilter = cfg[common.LDAPFilter].(string)
ldapConf.LdapScope = int(cfg[common.LDAPScope].(float64))
ldapConf.LdapConnectionTimeout = int(cfg[common.LDAPTimeout].(float64))
if cfg[common.LDAPVerifyCert] != nil {
ldapConf.LdapVerifyCert = cfg[common.LDAPVerifyCert].(bool)
} else {
ldapConf.LdapVerifyCert = true
}
return ldapConf, nil
}
// LDAPGroupConf returns the setting of ldap group search
func LDAPGroupConf() (*models.LdapGroupConf, error) {
cfg, err := mg.Get()
if err != nil {
return nil, err
}
ldapGroupConf := &models.LdapGroupConf{LdapGroupSearchScope: 2}
if _, ok := cfg[common.LDAPGroupBaseDN]; ok {
ldapGroupConf.LdapGroupBaseDN = cfg[common.LDAPGroupBaseDN].(string)
}
if _, ok := cfg[common.LDAPGroupSearchFilter]; ok {
ldapGroupConf.LdapGroupFilter = cfg[common.LDAPGroupSearchFilter].(string)
}
if _, ok := cfg[common.LDAPGroupAttributeName]; ok {
ldapGroupConf.LdapGroupNameAttribute = cfg[common.LDAPGroupAttributeName].(string)
}
if _, ok := cfg[common.LDAPGroupSearchScope]; ok {
if scopeStr, ok := cfg[common.LDAPGroupSearchScope].(string); ok {
ldapGroupConf.LdapGroupSearchScope, err = strconv.Atoi(scopeStr)
}
if scopeFloat, ok := cfg[common.LDAPGroupSearchScope].(float64); ok {
ldapGroupConf.LdapGroupSearchScope = int(scopeFloat)
}
}
return ldapGroupConf, nil
}
// TokenExpiration returns the token expiration time (in minute)
func TokenExpiration() (int, error) {
cfg, err := mg.Get()
if err != nil {
return 0, err
}
return int(cfg[common.TokenExpiration].(float64)), nil
}
// ExtEndpoint returns the external URL of Harbor: protocol://host:port
func ExtEndpoint() (string, error) {
cfg, err := mg.Get()
if err != nil {
return "", err
}
return cfg[common.ExtEndpoint].(string), nil
}
// ExtURL returns the external URL: host:port
func ExtURL() (string, error) {
endpoint, err := ExtEndpoint()
if err != nil {
return "", err
}
l := strings.Split(endpoint, "://")
if len(l) > 0 {
return l[1], nil
}
return endpoint, nil
}
// SecretKey returns the secret key to encrypt the password of target
func SecretKey() (string, error) {
return keyProvider.Get(nil)
}
// SelfRegistration returns the enablement of self registration
func SelfRegistration() (bool, error) {
cfg, err := mg.Get()
if err != nil {
return false, err
}
return cfg[common.SelfRegistration].(bool), nil
}
// RegistryURL ...
func RegistryURL() (string, error) {
cfg, err := mg.Get()
if err != nil {
return "", err
}
return cfg[common.RegistryURL].(string), nil
}
// InternalJobServiceURL returns jobservice URL for internal communication between Harbor containers
func InternalJobServiceURL() string {
cfg, err := mg.Get()
if err != nil {
log.Warningf("Failed to Get job service URL from backend, error: %v, will return default value.")
return common.DefaultJobserviceEndpoint
}
if cfg[common.JobServiceURL] == nil {
return common.DefaultJobserviceEndpoint
}
return strings.TrimSuffix(cfg[common.JobServiceURL].(string), "/")
}
// InternalUIURL returns the local ui url
func InternalUIURL() string {
cfg, err := mg.Get()
if err != nil {
log.Warningf("Failed to Get job service UI URL from backend, error: %v, will return default value.")
return common.DefaultUIEndpoint
}
return strings.TrimSuffix(cfg[common.UIURL].(string), "/")
}
// InternalTokenServiceEndpoint returns token service endpoint for internal communication between Harbor containers
func InternalTokenServiceEndpoint() string {
return InternalUIURL() + "/service/token"
}
// InternalNotaryEndpoint returns notary server endpoint for internal communication between Harbor containers
// This is currently a conventional value and can be unaccessible when Harbor is not deployed with Notary.
func InternalNotaryEndpoint() string {
cfg, err := mg.Get()
if err != nil {
log.Warningf("Failed to get Notary endpoint from backend, error: %v, will use default value.")
return common.DefaultNotaryEndpoint
}
if cfg[common.NotaryURL] == nil {
return common.DefaultNotaryEndpoint
}
return cfg[common.NotaryURL].(string)
}
// InitialAdminPassword returns the initial password for administrator
func InitialAdminPassword() (string, error) {
cfg, err := mg.Get()
if err != nil {
return "", err
}
return cfg[common.AdminInitialPassword].(string), nil
}
// OnlyAdminCreateProject returns the flag to restrict that only sys admin can create project
func OnlyAdminCreateProject() (bool, error) {
cfg, err := mg.Get()
if err != nil {
return true, err
}
return cfg[common.ProjectCreationRestriction].(string) == common.ProCrtRestrAdmOnly, nil
}
// Email returns email server settings
func Email() (*models.Email, error) {
cfg, err := mg.Get()
if err != nil {
return nil, err
}
email := &models.Email{}
email.Host = cfg[common.EmailHost].(string)
email.Port = int(cfg[common.EmailPort].(float64))
email.Username = cfg[common.EmailUsername].(string)
email.Password = cfg[common.EmailPassword].(string)
email.SSL = cfg[common.EmailSSL].(bool)
email.From = cfg[common.EmailFrom].(string)
email.Identity = cfg[common.EmailIdentity].(string)
email.Insecure = cfg[common.EmailInsecure].(bool)
return email, nil
}
// Database returns database settings
func Database() (*models.Database, error) {
cfg, err := mg.Get()
if err != nil {
return nil, err
}
database := &models.Database{}
database.Type = cfg[common.DatabaseType].(string)
mysql := &models.MySQL{}
mysql.Host = cfg[common.MySQLHost].(string)
mysql.Port = int(cfg[common.MySQLPort].(float64))
mysql.Username = cfg[common.MySQLUsername].(string)
mysql.Password = cfg[common.MySQLPassword].(string)
mysql.Database = cfg[common.MySQLDatabase].(string)
database.MySQL = mysql
sqlite := &models.SQLite{}
sqlite.File = cfg[common.SQLiteFile].(string)
database.SQLite = sqlite
return database, nil
}
// UISecret returns a secret to mark UI when communicate with
// other component
func UISecret() string {
return os.Getenv("UI_SECRET")
}
// JobserviceSecret returns a secret to mark Jobservice when communicate with
// other component
// TODO replace it with method of SecretStore
func JobserviceSecret() string {
return os.Getenv("JOBSERVICE_SECRET")
}
// WithNotary returns a bool value to indicate if Harbor's deployed with Notary
func WithNotary() bool {
cfg, err := mg.Get()
if err != nil {
log.Warningf("Failed to get configuration, will return WithNotary == false")
return false
}
return cfg[common.WithNotary].(bool)
}
// WithClair returns a bool value to indicate if Harbor's deployed with Clair
func WithClair() bool {
cfg, err := mg.Get()
if err != nil {
log.Errorf("Failed to get configuration, will return WithClair == false")
return false
}
return cfg[common.WithClair].(bool)
}
// ClairEndpoint returns the end point of clair instance, by default it's the one deployed within Harbor.
func ClairEndpoint() string {
cfg, err := mg.Get()
if err != nil {
log.Errorf("Failed to get configuration, use default clair endpoint")
return common.DefaultClairEndpoint
}
return cfg[common.ClairURL].(string)
}
// ClairDB return Clair db info
func ClairDB() (*models.PostGreSQL, error) {
cfg, err := mg.Get()
if err != nil {
log.Errorf("Failed to get configuration of Clair DB, Error detail %v", err)
return nil, err
}
clairDB := &models.PostGreSQL{}
clairDB.Host = cfg[common.ClairDBHost].(string)
clairDB.Port = int(cfg[common.ClairDBPort].(float64))
clairDB.Username = cfg[common.ClairDBUsername].(string)
clairDB.Password = cfg[common.ClairDBPassword].(string)
clairDB.Database = cfg[common.ClairDB].(string)
return clairDB, nil
}
// AdmiralEndpoint returns the URL of admiral, if Harbor is not deployed with admiral it should return an empty string.
func AdmiralEndpoint() string {
cfg, err := mg.Get()
if err != nil {
log.Errorf("Failed to get configuration, will return empty string as admiral's endpoint, error: %v", err)
return ""
}
if e, ok := cfg[common.AdmiralEndpoint].(string); !ok || e == "NA" {
return ""
}
return cfg[common.AdmiralEndpoint].(string)
}
// ScanAllPolicy returns the policy which controls the scan all.
func ScanAllPolicy() models.ScanAllPolicy {
var res models.ScanAllPolicy
cfg, err := mg.Get()
if err != nil {
log.Errorf("Failed to get configuration, will return default scan all policy, error: %v", err)
return models.DefaultScanAllPolicy
}
v, ok := cfg[common.ScanAllPolicy]
if !ok {
return models.DefaultScanAllPolicy
}
b, err := json.Marshal(v)
if err != nil {
log.Errorf("Failed to Marshal the value in configuration for Scan All policy, error: %v, returning the default policy", err)
return models.DefaultScanAllPolicy
}
if err := json.Unmarshal(b, &res); err != nil {
log.Errorf("Failed to unmarshal the value in configuration for Scan All policy, error: %v, returning the default policy", err)
return models.DefaultScanAllPolicy
}
return res
}
// WithAdmiral returns a bool to indicate if Harbor's deployed with admiral.
func WithAdmiral() bool {
return len(AdmiralEndpoint()) > 0
}
//UAASettings returns the UAASettings to access UAA service.
func UAASettings() (*models.UAASettings, error) {
cfg, err := mg.Get()
if err != nil {
return nil, err
}
us := &models.UAASettings{
Endpoint: cfg[common.UAAEndpoint].(string),
ClientID: cfg[common.UAAClientID].(string),
ClientSecret: cfg[common.UAAClientSecret].(string),
VerifyCert: cfg[common.UAAVerifyCert].(bool),
}
return us, nil
}
// ReadOnly returns a bool to indicates if Harbor is in read only mode.
func ReadOnly() bool {
cfg, err := mg.Get()
if err != nil {
log.Errorf("Failed to get configuration, will return false as read only, error: %v", err)
return false
}
return cfg[common.ReadOnly].(bool)
}