-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
executable file
·1453 lines (1285 loc) · 48.3 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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package controller
import (
"fmt"
"net/url"
"regexp"
"time"
"github.com/go-macaroon-bakery/macaroon-bakery/v3/bakery"
"github.com/juju/charmrepo/v6/csclient"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names/v4"
"github.com/juju/romulus"
"github.com/juju/schema"
"github.com/juju/utils/v2"
"gopkg.in/juju/environschema.v1"
"github.com/juju/juju/docker"
"github.com/juju/juju/docker/registry"
"github.com/juju/juju/pki"
)
var logger = loggo.GetLogger("juju.controller")
const (
// MongoProfLow represents the most conservative mongo memory profile.
MongoProfLow = "low"
// MongoProfDefault represents the mongo memory profile shipped by default.
MongoProfDefault = "default"
)
const (
// APIPort is the port used for api connections.
APIPort = "api-port"
// ControllerAPIPort is an optional port that may be set for controllers
// that have a very heavy load. If this port is set, this port is used by
// the controllers to talk to each other - used for the local API connection
// as well as the pubsub forwarders, and the raft workers. If this value is
// set, the api-port isn't opened until the controllers have started
// properly.
ControllerAPIPort = "controller-api-port"
// Canonical name for the controller
ControllerName = "controller-name"
// AgentRateLimitMax is the maximum size of the token bucket used to
// ratelimit the agent connections.
AgentRateLimitMax = "agent-ratelimit-max"
// AgentRateLimitRate is the time taken to add a new token to the bucket.
// This effectively says that we can have a new agent connect per duration specified.
AgentRateLimitRate = "agent-ratelimit-rate"
// APIPortOpenDelay is a duration that the controller will wait
// between when the controller has been deemed to be ready to open
// the api-port and when the api-port is actually opened. This value
// is only used when a controller-api-port value is set.
APIPortOpenDelay = "api-port-open-delay"
// AuditingEnabled determines whether the controller will record
// auditing information.
AuditingEnabled = "auditing-enabled"
// AuditLogCaptureArgs determines whether the audit log will
// contain the arguments passed to API methods.
AuditLogCaptureArgs = "audit-log-capture-args"
// AuditLogMaxSize is the maximum size for the current audit log
// file, eg "250M".
AuditLogMaxSize = "audit-log-max-size"
// AuditLogMaxBackups is the number of old audit log files to keep
// (compressed).
AuditLogMaxBackups = "audit-log-max-backups"
// AuditLogExcludeMethods is a list of Facade.Method names that
// aren't interesting for audit logging purposes. A conversation
// with only calls to these will be excluded from the
// log. (They'll still appear in conversations that have other
// interesting calls though.)
AuditLogExcludeMethods = "audit-log-exclude-methods"
// ReadOnlyMethodsWildcard is the special value that can be added
// to the exclude-methods list that represents all of the read
// only methods (see apiserver/observer/auditfilter.go). This
// value will be stored in the DB (rather than being expanded at
// write time) so any changes to the set of read-only methods in
// new versions of Juju will be honoured.
ReadOnlyMethodsWildcard = "ReadOnlyMethods"
// StatePort is the port used for mongo connections.
StatePort = "state-port"
// CACertKey is the key for the controller's CA certificate attribute.
CACertKey = "ca-cert"
// CharmStoreURL is the key for the url to use for charmstore API calls
CharmStoreURL = "charmstore-url"
// ControllerUUIDKey is the key for the controller UUID attribute.
ControllerUUIDKey = "controller-uuid"
// IdentityURL sets the url of the identity manager.
IdentityURL = "identity-url"
// IdentityPublicKey sets the public key of the identity manager.
IdentityPublicKey = "identity-public-key"
// SetNUMAControlPolicyKey stores the value for this setting
SetNUMAControlPolicyKey = "set-numa-control-policy"
// AutocertDNSNameKey sets the DNS name of the controller. If a
// client connects to this name, an official certificate will be
// automatically requested. Connecting to any other host name
// will use the usual self-generated certificate.
AutocertDNSNameKey = "autocert-dns-name"
// AutocertURLKey sets the URL used to obtain official TLS
// certificates when a client connects to the API. By default,
// certficates are obtains from LetsEncrypt. A good value for
// testing is
// "https://acme-staging.api.letsencrypt.org/directory".
AutocertURLKey = "autocert-url"
// AllowModelAccessKey sets whether the controller will allow users to
// connect to models they have been authorized for even when
// they don't have any access rights to the controller itself.
AllowModelAccessKey = "allow-model-access"
// MongoMemoryProfile sets whether mongo uses the least possible memory or the
// detault
MongoMemoryProfile = "mongo-memory-profile"
// JujuDBSnapChannel selects the channel to use when installing mongo
// snaps for focal or later. The value is ignored for older releases.
JujuDBSnapChannel = "juju-db-snap-channel"
// MaxDebugLogDuration is used to provide a backstop to the execution of a
// debug-log command. If someone starts a debug-log session in a remote
// screen for example, it is very easy to disconnect from the screen while
// leaving the debug-log process running. This causes unnecessary load on
// the API Server. The max debug-log duration has a default of 24 hours,
// which should be more than enough time for a debugging session.
// If the user needs more information, perhaps debug-log isn't the right source.
MaxDebugLogDuration = "max-debug-log-duration"
// ModelLogfileMaxSize is the maximum size of the log file written out by the
// controller on behalf of workers running for a model.
ModelLogfileMaxSize = "model-logfile-max-size"
// ModelLogfileMaxBackups is the number of old model
// log files to keep (compressed).
ModelLogfileMaxBackups = "model-logfile-max-backups"
// ModelLogsSize is the size of the capped collections used to hold the
// logs for the models, eg "20M". Size is per model.
ModelLogsSize = "model-logs-size"
// MaxTxnLogSize is the maximum size the of capped txn log collection, eg "10M"
MaxTxnLogSize = "max-txn-log-size"
// MaxPruneTxnBatchSize (deprecated) is the maximum number of transactions
// we will evaluate in one go when pruning. Default is 1M transactions.
// A value <= 0 indicates to do all transactions at once.
MaxPruneTxnBatchSize = "max-prune-txn-batch-size"
// MaxPruneTxnPasses (deprecated) is the maximum number of batches that
// we will process. So total number of transactions that can be processed
// is MaxPruneTxnBatchSize * MaxPruneTxnPasses. A value <= 0 implies
// 'do a single pass'. If both MaxPruneTxnBatchSize and MaxPruneTxnPasses
// are 0, then the default value of 1M BatchSize and 100 passes
// will be used instead.
MaxPruneTxnPasses = "max-prune-txn-passes"
// PruneTxnQueryCount is the number of transactions to read in a single query.
// Minimum of 10, a value of 0 will indicate to use the default value (1000)
PruneTxnQueryCount = "prune-txn-query-count"
// PruneTxnSleepTime is the amount of time to sleep between processing each
// batch query. This is used to reduce load on the system, allowing other
// queries to time to operate. On large controllers, processing 1000 txs
// seems to take about 100ms, so a sleep time of 10ms represents a 10%
// slowdown, but allows other systems to operate concurrently.
// A negative number will indicate to use the default, a value of 0
// indicates to not sleep at all.
PruneTxnSleepTime = "prune-txn-sleep-time"
// MaxCharmStateSize is the maximum allowed size of charm-specific
// per-unit state data that charms can store to the controller in
// bytes. A value of 0 disables the quota checks although in
// principle, mongo imposes a hard (but configurable) limit of 16M.
MaxCharmStateSize = "max-charm-state-size"
// MaxAgentStateSize is the maximum allowed size of internal state
// data that agents can store to the controller in bytes. A value of 0
// disables the quota checks although in principle, mongo imposes a
// hard (but configurable) limit of 16M.
MaxAgentStateSize = "max-agent-state-size"
// NonSyncedWritesToRaftLog allows the operator to disable fsync calls
// when writing to the raft log by setting this value to true.
NonSyncedWritesToRaftLog = "non-synced-writes-to-raft-log"
// MigrationMinionWaitMax is the maximum time that the migration-master
// worker will wait for agents to report for a migration phase when
// executing a model migration.
MigrationMinionWaitMax = "migration-agent-wait-time"
// JujuHASpace is the network space within which the MongoDB replica-set
// should communicate.
JujuHASpace = "juju-ha-space"
// JujuManagementSpace is the network space that agents should use to
// communicate with controllers.
JujuManagementSpace = "juju-mgmt-space"
// CAASOperatorImagePath sets the url of the docker image
// used for the application operator.
// Deprecated: use CAASImageRepo
CAASOperatorImagePath = "caas-operator-image-path"
// CAASImageRepo sets the docker repo to use
// for the jujud operator and mongo images.
CAASImageRepo = "caas-image-repo"
// Features allows a list of runtime changeable features to be updated.
Features = "features"
// MeteringURL is the key for the url to use for metrics
MeteringURL = "metering-url"
// PublicDNSAddress is the public DNS address (and port) of the controller.
PublicDNSAddress = "public-dns-address"
// Attribute Defaults
// DefaultAgentRateLimitMax allows the first 10 agents to connect without
// any issue. After that the rate limiting kicks in.
DefaultAgentRateLimitMax = 10
// DefaultAgentRateLimitRate will allow four agents to connect every
// second. A token is added to the ratelimit token bucket every 250ms.
DefaultAgentRateLimitRate = 250 * time.Millisecond
// DefaultAuditingEnabled contains the default value for the
// AuditingEnabled config value.
DefaultAuditingEnabled = true
// DefaultAuditLogCaptureArgs is the default for the
// AuditLogCaptureArgs setting (which is not to capture them).
DefaultAuditLogCaptureArgs = false
// DefaultAuditLogMaxSizeMB is the default size in MB at which we
// roll the audit log file.
DefaultAuditLogMaxSizeMB = 300
// DefaultAuditLogMaxBackups is the default number of files to
// keep.
DefaultAuditLogMaxBackups = 10
// DefaultNUMAControlPolicy should not be used by default.
// Only use numactl if user specifically requests it
DefaultNUMAControlPolicy = false
// DefaultStatePort is the default port the controller is listening on.
DefaultStatePort int = 37017
// DefaultAPIPort is the default port the API server is listening on.
DefaultAPIPort int = 17070
// DefaultAPIPortOpenDelay is the default value for api-port-open-delay.
// It is a string representation of a time.Duration.
DefaultAPIPortOpenDelay = "2s"
// DefaultMongoMemoryProfile is the default profile used by mongo.
DefaultMongoMemoryProfile = MongoProfDefault
// DefaultJujuDBSnapChannel is the default snap channel for installing
// mongo in focal or later.
DefaultJujuDBSnapChannel = "4.0/stable"
// DefaultMaxDebugLogDuration is the default duration that debug-log
// commands can run before being terminated by the API server.
DefaultMaxDebugLogDuration = 24 * time.Hour
// DefaultMaxTxnLogCollectionMB is the maximum size the txn log collection.
DefaultMaxTxnLogCollectionMB = 10 // 10 MB
// DefaultMaxPruneTxnBatchSize is the normal number of transaction
// we will prune in a given pass (1M) (deprecated)
DefaultMaxPruneTxnBatchSize = 1 * 1000 * 1000
// DefaultMaxPruneTxnPasses is the default number of
// batches we will process. (deprecated)
DefaultMaxPruneTxnPasses = 100
// DefaultModelLogfileMaxSize is the maximum file size in MB of
// the log file written out by the controller on behalf of workers
// running for a model.
DefaultModelLogfileMaxSize = 10
// DefaultModelLogfileMaxBackups is the number of old model
// log files to keep (compressed).
DefaultModelLogfileMaxBackups = 2
// DefaultModelLogsSizeMB is the size in MB of the capped logs collection
// for each model.
DefaultModelLogsSizeMB = 20
// DefaultPruneTxnQueryCount is the number of transactions
// to read in a single query.
DefaultPruneTxnQueryCount = 1000
// DefaultPruneTxnSleepTime is the amount of time to sleep between
// processing each batch query. This is used to reduce load on the system,
// allowing other queries to time to operate. On large controllers,
// processing 1000 txs seems to take about 100ms, so a sleep time of 10ms
// represents a 10% slowdown, but allows other systems to
// operate concurrently.
DefaultPruneTxnSleepTime = "10ms"
// DefaultMaxCharmStateSize is the maximum size (in bytes) of charm
// state data that each unit can store to the controller.
DefaultMaxCharmStateSize = 2 * 1024 * 1024
// DefaultMaxAgentStateSize is the maximum size (in bytes) of internal
// state data that agents can store to the controller.
DefaultMaxAgentStateSize = 512 * 1024
// DefaultNonSyncedWritesToRaftLog is the default value for the
// non-synced-writes-to-raft-log value. It is set to false by default.
DefaultNonSyncedWritesToRaftLog = false
// DefaultMigrationMinionMaxWait is the default value for
DefaultMigrationMinionWaitMax = "15m"
)
var (
// ControllerOnlyConfigAttributes are attributes which are only relevant
// for a controller, never a model.
ControllerOnlyConfigAttributes = []string{
AllowModelAccessKey,
AgentRateLimitMax,
AgentRateLimitRate,
APIPort,
APIPortOpenDelay,
AutocertDNSNameKey,
AutocertURLKey,
CACertKey,
CharmStoreURL,
ControllerAPIPort,
ControllerName,
ControllerUUIDKey,
IdentityPublicKey,
IdentityURL,
SetNUMAControlPolicyKey,
StatePort,
MongoMemoryProfile,
JujuDBSnapChannel,
MaxDebugLogDuration,
MaxTxnLogSize,
MaxPruneTxnBatchSize,
MaxPruneTxnPasses,
ModelLogfileMaxBackups,
ModelLogfileMaxSize,
ModelLogsSize,
PruneTxnQueryCount,
PruneTxnSleepTime,
PublicDNSAddress,
JujuHASpace,
JujuManagementSpace,
AuditingEnabled,
AuditLogCaptureArgs,
AuditLogMaxSize,
AuditLogMaxBackups,
AuditLogExcludeMethods,
CAASOperatorImagePath,
CAASImageRepo,
Features,
MeteringURL,
MaxCharmStateSize,
MaxAgentStateSize,
NonSyncedWritesToRaftLog,
MigrationMinionWaitMax,
}
// For backwards compatibility, we must include "anything", "juju-apiserver"
// and "juju-mongodb" as hostnames as that is what clients specify
// as the hostname for verification (this certificate is used both
// for serving MongoDB and API server connections). We also
// explicitly include localhost.
DefaultDNSNames = []string{
"localhost",
"juju-apiserver",
"juju-mongodb",
"anything",
}
// AllowedUpdateConfigAttributes contains all of the controller
// config attributes that are allowed to be updated after the
// controller has been created.
AllowedUpdateConfigAttributes = set.NewStrings(
AgentRateLimitMax,
AgentRateLimitRate,
APIPortOpenDelay,
AuditingEnabled,
AuditLogCaptureArgs,
AuditLogExcludeMethods,
// TODO Juju 3.0: ControllerAPIPort should be required and treated
// more like api-port.
ControllerAPIPort,
ControllerName,
MaxDebugLogDuration,
MaxPruneTxnBatchSize,
MaxPruneTxnPasses,
ModelLogfileMaxBackups,
ModelLogfileMaxSize,
ModelLogsSize,
MongoMemoryProfile,
PruneTxnQueryCount,
PruneTxnSleepTime,
PublicDNSAddress,
JujuHASpace,
JujuManagementSpace,
Features,
MaxCharmStateSize,
MaxAgentStateSize,
NonSyncedWritesToRaftLog,
MigrationMinionWaitMax,
)
// DefaultAuditLogExcludeMethods is the default list of methods to
// exclude from the audit log.
DefaultAuditLogExcludeMethods = []string{
// This special value means we exclude any methods in the set
// listed in apiserver/observer/auditfilter.go
ReadOnlyMethodsWildcard,
}
methodNameRE = regexp.MustCompile(`[[:alpha:]][[:alnum:]]*\.[[:alpha:]][[:alnum:]]*`)
)
// ControllerOnlyAttribute returns true if the specified attribute name
// is only relevant for a controller.
func ControllerOnlyAttribute(attr string) bool {
for _, a := range ControllerOnlyConfigAttributes {
if attr == a {
return true
}
}
return false
}
// Config is a string-keyed map of controller configuration attributes.
type Config map[string]interface{}
// Validate validates the controller configuration.
func (c Config) Validate() error {
return Validate(c)
}
// NewConfig creates a new Config from the supplied attributes.
// Default values will be used where defaults are available.
//
// The controller UUID and CA certificate must be passed in.
// The UUID is typically generated by the immediate caller,
// and the CA certificate generated by environs/bootstrap.NewConfig.
func NewConfig(controllerUUID, caCert string, attrs map[string]interface{}) (Config, error) {
coerced, err := configChecker.Coerce(attrs, nil)
if err != nil {
return Config{}, errors.Trace(err)
}
attrs = coerced.(map[string]interface{})
attrs[ControllerUUIDKey] = controllerUUID
attrs[CACertKey] = caCert
config := Config(attrs)
return config, config.Validate()
}
// mustInt returns the named attribute as an integer, panicking if
// it is not found or is zero. Zero values should have been
// diagnosed at Validate time.
func (c Config) mustInt(name string) int {
// Values obtained over the api are encoded as float64.
if value, ok := c[name].(float64); ok {
return int(value)
}
value, _ := c[name].(int)
if value == 0 {
panic(errors.Errorf("empty value for %q found in configuration", name))
}
return value
}
func (c Config) intOrDefault(name string, defaultVal int) int {
if _, ok := c[name]; ok {
return c.mustInt(name)
}
return defaultVal
}
func (c Config) sizeMBOrDefault(name string, defaultVal int) int {
size := c.asString(name)
if size != "" {
// Value has already been validated.
value, _ := utils.ParseSize(size)
return int(value)
}
return defaultVal
}
// asString is a private helper method to keep the ugly string casting
// in once place. It returns the given named attribute as a string,
// returning "" if it isn't found.
func (c Config) asString(name string) string {
value, _ := c[name].(string)
return value
}
// mustString returns the named attribute as an string, panicking if
// it is not found or is empty.
func (c Config) mustString(name string) string {
value, _ := c[name].(string)
if value == "" {
panic(errors.Errorf("empty value for %q found in configuration (type %T, val %v)", name, c[name], c[name]))
}
return value
}
func (c Config) durationOrDefault(name string, defaultVal time.Duration) time.Duration {
switch v := c[name].(type) {
case string:
if v != "" {
// Value has already been validated.
value, _ := time.ParseDuration(v)
return value
}
case time.Duration:
return v
default:
// nil type shows up here
}
return defaultVal
}
// StatePort returns the mongo server port for the environment.
func (c Config) StatePort() int {
return c.mustInt(StatePort)
}
// APIPort returns the API server port for the environment.
func (c Config) APIPort() int {
return c.mustInt(APIPort)
}
// APIPortOpenDelay returns the duration to wait before opening
// the APIPort once the controller has started up. Only used when
// the ControllerAPIPort is non-zero.
func (c Config) APIPortOpenDelay() time.Duration {
v := c.asString(APIPortOpenDelay)
// We know that v must be a parseable time.Duration for the config
// to be valid.
d, _ := time.ParseDuration(v)
return d
}
// ControllerAPIPort returns the optional API port to be used for
// the controllers to talk to each other. A zero value means that
// it is not set.
func (c Config) ControllerAPIPort() int {
if value, ok := c[ControllerAPIPort].(float64); ok {
return int(value)
}
// If the value isn't an int, this conversion will fail and value
// will be 0, which is what we want here.
value, _ := c[ControllerAPIPort].(int)
return value
}
// AgentRateLimitMax is the initial size of the token bucket that is used to
// rate limit agent connections.
func (c Config) AgentRateLimitMax() int {
switch v := c[AgentRateLimitMax].(type) {
case float64:
return int(v)
case int:
return v
default:
// nil type shows up here
}
return DefaultAgentRateLimitMax
}
// AgentRateLimitRate is the time taken to add a token into the token bucket
// that is used to rate limit agent connections.
func (c Config) AgentRateLimitRate() time.Duration {
return c.durationOrDefault(AgentRateLimitRate, DefaultAgentRateLimitRate)
}
// AuditingEnabled returns whether or not auditing has been enabled
// for the environment. The default is false.
func (c Config) AuditingEnabled() bool {
if v, ok := c[AuditingEnabled]; ok {
return v.(bool)
}
return DefaultAuditingEnabled
}
// AuditLogCaptureArgs returns whether audit logging should capture
// the arguments to API methods. The default is false.
func (c Config) AuditLogCaptureArgs() bool {
if v, ok := c[AuditLogCaptureArgs]; ok {
return v.(bool)
}
return DefaultAuditLogCaptureArgs
}
// AuditLogMaxSizeMB returns the maximum size for an audit log file in
// MB.
func (c Config) AuditLogMaxSizeMB() int {
return c.sizeMBOrDefault(AuditLogMaxSize, DefaultAuditLogMaxSizeMB)
}
// AuditLogMaxBackups returns the maximum number of backup audit log
// files to keep.
func (c Config) AuditLogMaxBackups() int {
return c.intOrDefault(AuditLogMaxBackups, DefaultAuditLogMaxBackups)
}
// AuditLogExcludeMethods returns the set of method names that are
// considered uninteresting for audit logging. Conversations
// containing only these will be excluded from the audit log.
func (c Config) AuditLogExcludeMethods() set.Strings {
if value, ok := c[AuditLogExcludeMethods]; ok {
value := value.([]interface{})
items := set.NewStrings()
for _, item := range value {
items.Add(item.(string))
}
return items
}
return set.NewStrings(DefaultAuditLogExcludeMethods...)
}
// Features returns the controller config set features flags.
func (c Config) Features() set.Strings {
features := set.NewStrings()
if value, ok := c[Features]; ok {
value := value.([]interface{})
for _, item := range value {
features.Add(item.(string))
}
}
return features
}
// CharmStoreURL returns the URL to use for charmstore api calls.
func (c Config) CharmStoreURL() string {
url := c.asString(CharmStoreURL)
if url == "" {
return csclient.ServerURL
}
return url
}
// ControllerName returns the name for the controller
func (c Config) ControllerName() string {
return c.asString(ControllerName)
}
// ControllerUUID returns the uuid for the controller.
func (c Config) ControllerUUID() string {
return c.mustString(ControllerUUIDKey)
}
// CACert returns the certificate of the CA that signed the controller
// certificate, in PEM format, and whether the setting is available.
//
// TODO(axw) once the controller config is completely constructed,
// there will always be a CA certificate. Get rid of the bool result.
func (c Config) CACert() (string, bool) {
if s, ok := c[CACertKey]; ok {
return s.(string), true
}
return "", false
}
// IdentityURL returns the url of the identity manager.
func (c Config) IdentityURL() string {
return c.asString(IdentityURL)
}
// AutocertURL returns the URL used to obtain official TLS certificates
// when a client connects to the API. See AutocertURLKey
// for more details.
func (c Config) AutocertURL() string {
return c.asString(AutocertURLKey)
}
// AutocertDNSName returns the DNS name of the controller.
// See AutocertDNSNameKey for more details.
func (c Config) AutocertDNSName() string {
return c.asString(AutocertDNSNameKey)
}
// IdentityPublicKey returns the public key of the identity manager.
func (c Config) IdentityPublicKey() *bakery.PublicKey {
key := c.asString(IdentityPublicKey)
if key == "" {
return nil
}
var pubKey bakery.PublicKey
err := pubKey.UnmarshalText([]byte(key))
if err != nil {
// We check if the key string can be unmarshalled into a PublicKey in the
// Validate function, so we really do not expect this to fail.
panic(err)
}
return &pubKey
}
// MongoMemoryProfile returns the selected profile or low.
func (c Config) MongoMemoryProfile() string {
if profile, ok := c[MongoMemoryProfile]; ok {
return profile.(string)
}
return DefaultMongoMemoryProfile
}
// JujuDBSnapChannel returns the channel for installing mongo snaps.
func (c Config) JujuDBSnapChannel() string {
return c.asString(JujuDBSnapChannel)
}
// NUMACtlPreference returns if numactl is preferred.
func (c Config) NUMACtlPreference() bool {
if numa, ok := c[SetNUMAControlPolicyKey]; ok {
return numa.(bool)
}
return DefaultNUMAControlPolicy
}
// AllowModelAccess reports whether users are allowed to access models
// they have been granted permission for even when they can't access
// the controller.
func (c Config) AllowModelAccess() bool {
value, _ := c[AllowModelAccessKey].(bool)
return value
}
// ModelLogfileMaxBackups is the number of old model log files to keep (compressed).
func (c Config) ModelLogfileMaxBackups() int {
return c.intOrDefault(ModelLogfileMaxBackups, DefaultModelLogfileMaxBackups)
}
// ModelLogfileMaxSizeMB is the maximum size of the log file written out by the
// controller on behalf of workers running for a model.
func (c Config) ModelLogfileMaxSizeMB() int {
return c.sizeMBOrDefault(ModelLogfileMaxSize, DefaultModelLogfileMaxSize)
}
// ModelLogsSizeMB is the size of the capped collection used to store the model
// logs. Total size on disk will be ModelLogsSizeMB * number of models.
func (c Config) ModelLogsSizeMB() int {
return c.sizeMBOrDefault(ModelLogsSize, DefaultModelLogsSizeMB)
}
// MaxDebugLogDuration is the maximum time a debug-log session is allowed
// to run before it is terminated by the server.
func (c Config) MaxDebugLogDuration() time.Duration {
duration, ok := c[MaxDebugLogDuration].(time.Duration)
if !ok {
duration = DefaultMaxDebugLogDuration
}
return duration
}
// MaxTxnLogSizeMB is the maximum size in MiB of the txn log collection.
func (c Config) MaxTxnLogSizeMB() int {
return c.sizeMBOrDefault(MaxTxnLogSize, DefaultMaxTxnLogCollectionMB)
}
// MaxPruneTxnBatchSize is the maximum size of the txn log collection.
func (c Config) MaxPruneTxnBatchSize() int {
return c.intOrDefault(MaxPruneTxnBatchSize, DefaultMaxPruneTxnBatchSize)
}
// MaxPruneTxnPasses is the maximum number of batches of the txn log collection we will process at a time.
func (c Config) MaxPruneTxnPasses() int {
return c.intOrDefault(MaxPruneTxnPasses, DefaultMaxPruneTxnPasses)
}
// PruneTxnQueryCount is the size of small batches for pruning
func (c Config) PruneTxnQueryCount() int {
return c.intOrDefault(PruneTxnQueryCount, DefaultPruneTxnQueryCount)
}
// PruneTxnSleepTime is the amount of time to sleep between batches.
func (c Config) PruneTxnSleepTime() time.Duration {
asInterface, ok := c[PruneTxnSleepTime]
if !ok {
asInterface = DefaultPruneTxnSleepTime
}
asStr, ok := asInterface.(string)
if !ok {
asStr = DefaultPruneTxnSleepTime
}
val, _ := time.ParseDuration(asStr)
return val
}
// PublicDNSAddress returns the DNS name of the controller.
func (c Config) PublicDNSAddress() string {
return c.asString(PublicDNSAddress)
}
// JujuHASpace is the network space within which the MongoDB replica-set
// should communicate.
func (c Config) JujuHASpace() string {
return c.asString(JujuHASpace)
}
// JujuManagementSpace is the network space that agents should use to
// communicate with controllers.
func (c Config) JujuManagementSpace() string {
return c.asString(JujuManagementSpace)
}
// CAASOperatorImagePath sets the url of the docker image
// used for the application operator.
func (c Config) CAASOperatorImagePath() (o docker.ImageRepoDetails) {
str := c.asString(CAASOperatorImagePath)
repoDetails, err := docker.NewImageRepoDetails(str)
if repoDetails != nil {
return *repoDetails
}
// This should not happen since we have done validation in c.Valiate().
logger.Tracef("parsing controller config %q: %q, err %v", CAASOperatorImagePath, str, err)
return o
}
func validateCAASImageRepo(imageRepo string) (string, error) {
if imageRepo == "" {
return "", nil
}
imageDetails, err := docker.NewImageRepoDetails(imageRepo)
if err != nil {
return "", errors.Trace(err)
}
if err = imageDetails.Validate(); err != nil {
return "", errors.Trace(err)
}
r, err := registry.New(*imageDetails)
if err != nil {
return "", errors.Trace(err)
}
defer func() { _ = r.Close() }()
if err = r.Ping(); err != nil {
return "", errors.Trace(err)
}
return r.ImageRepoDetails().Content(), nil
}
// CAASImageRepo sets the url of the docker repo
// used for the jujud operator and mongo images.
func (c Config) CAASImageRepo() (o docker.ImageRepoDetails) {
str := c.asString(CAASImageRepo)
repoDetails, err := docker.NewImageRepoDetails(str)
if repoDetails != nil {
return *repoDetails
}
// This should not happen since we have done validation in c.Valiate().
logger.Tracef("parsing controller config %q: %q, err %v", CAASImageRepo, str, err)
return o
}
// MeteringURL returns the URL to use for metering api calls.
func (c Config) MeteringURL() string {
url := c.asString(MeteringURL)
if url == "" {
return romulus.DefaultAPIRoot
}
return url
}
// MaxCharmStateSize returns the max size (in bytes) of charm-specific state
// that each unit can store to the controller. A value of zero indicates no
// limit.
func (c Config) MaxCharmStateSize() int {
return c.intOrDefault(MaxCharmStateSize, DefaultMaxCharmStateSize)
}
// MaxAgentStateSize returns the max size (in bytes) of state data that agents
// can store to the controller. A value of zero indicates no limit.
func (c Config) MaxAgentStateSize() int {
return c.intOrDefault(MaxAgentStateSize, DefaultMaxAgentStateSize)
}
// NonSyncedWritesToRaftLog returns true if fsync calls should be skipped
// after each write to the raft log.
func (c Config) NonSyncedWritesToRaftLog() bool {
if v, ok := c[NonSyncedWritesToRaftLog]; ok {
return v.(bool)
}
return DefaultNonSyncedWritesToRaftLog
}
// MigrationMinionWaitMax returns a duration for the maximum time that the
// migration-master worker should wait for migration-minion reports during
// phases of a model migration.
func (c Config) MigrationMinionWaitMax() time.Duration {
asInterface, ok := c[MigrationMinionWaitMax]
if !ok {
asInterface = DefaultMigrationMinionWaitMax
}
asStr, ok := asInterface.(string)
if !ok {
asStr = DefaultMigrationMinionWaitMax
}
val, _ := time.ParseDuration(asStr)
return val
}
// Validate ensures that config is a valid configuration.
func Validate(c Config) error {
if v, ok := c[IdentityPublicKey].(string); ok {
var key bakery.PublicKey
if err := key.UnmarshalText([]byte(v)); err != nil {
return errors.Annotate(err, "invalid identity public key")
}
}
if v, ok := c[IdentityURL].(string); ok {
u, err := url.Parse(v)
if err != nil {
return errors.Annotate(err, "invalid identity URL")
}
// If we've got an identity public key, we allow an HTTP
// scheme for the identity server because we won't need
// to rely on insecure transport to obtain the public
// key.
if _, ok := c[IdentityPublicKey]; !ok && u.Scheme != "https" {
return errors.Errorf("URL needs to be https when %s not provided", IdentityPublicKey)
}
}
caCert, caCertOK := c.CACert()
if !caCertOK {
return errors.Errorf("missing CA certificate")
}
if ok, err := pki.IsPemCA([]byte(caCert)); err != nil {
return errors.Annotate(err, "bad CA certificate in configuration")
} else if !ok {
return errors.New("ca certificate in configuration is not a CA")
}
if uuid, ok := c[ControllerUUIDKey].(string); ok && !utils.IsValidUUIDString(uuid) {
return errors.Errorf("controller-uuid: expected UUID, got string(%q)", uuid)
}
if v, ok := c[AgentRateLimitMax].(int); ok {
if v < 0 {
return errors.NotValidf("negative %s (%d)", AgentRateLimitMax, v)
}
}
if v, ok := c[AgentRateLimitRate].(time.Duration); ok {
if v == 0 {
return errors.Errorf("%s cannot be zero", AgentRateLimitRate)
}
if v < 0 {
return errors.Errorf("%s cannot be negative", AgentRateLimitRate)
}
if v > time.Minute {
return errors.Errorf("%s must be between 0..1m", AgentRateLimitRate)
}
}
if mgoMemProfile, ok := c[MongoMemoryProfile].(string); ok {
if mgoMemProfile != MongoProfLow && mgoMemProfile != MongoProfDefault {
return errors.Errorf("mongo-memory-profile: expected one of %q or %q got string(%q)", MongoProfLow, MongoProfDefault, mgoMemProfile)
}
}
if v, ok := c[MaxDebugLogDuration].(time.Duration); ok {
if v == 0 {
return errors.Errorf("%s cannot be zero", MaxDebugLogDuration)
}
}
if v, ok := c[ModelLogsSize].(string); ok {
mb, err := utils.ParseSize(v)
if err != nil {
return errors.Annotate(err, "invalid model logs size in configuration")