forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
558 lines (479 loc) · 14.5 KB
/
service.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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package mongo
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/juju/errors"
"github.com/juju/utils"
"github.com/juju/utils/featureflag"
"github.com/juju/utils/set"
"github.com/juju/juju/feature"
"github.com/juju/juju/network"
"github.com/juju/juju/service"
"github.com/juju/juju/service/common"
"github.com/juju/juju/service/snap"
)
const (
// ServiceName is the name of the service that Juju's mongod instance
// will be named.
ServiceName = "juju-db"
serviceTimeout = 300 // 5 minutes
// SharedSecretFile is the name of the Mongo shared secret file
// located within the Juju data directory.
SharedSecretFile = "shared-secret"
// ReplicaSetName is the name of the replica set that juju uses for its
// controllers.
ReplicaSetName = "juju"
// LowCacheSize expressed in GB sets the max value Mongo WiredTiger cache can
// reach.
LowCacheSize = 1
// Mongo34LowCacheSize changed to being a float, and allows you to specify down to 256MB
Mongo34LowCacheSize = 0.25
// flagMarker is an in-line comment for bash. If it somehow makes its way onto
// the command line, it will be ignored. See https://stackoverflow.com/a/1456019/395287
flagMarker = "`#flag: true` \\"
dataPathForJujuDbSnap = "/var/snap/juju-db/common"
// mongoLogPath is used as a fallback location when syslog is not enabled
mongoLogPath = "/var/log/mongodb"
// FileNameDBSSLKey is the file name of db ssl key file name.
FileNameDBSSLKey = "server.pem"
)
var (
// This is the name of an environment variable that we use in the
// init system conf file when mongo NUMA support is used.
multinodeVarName = "MULTI_NODE"
// This value will be used to wrap desired mongo cmd in numactl if wanted/needed
numaCtlWrap = "$%v"
// Extra shell script fragment for init script template.
// This determines if we are dealing with multi-node environment
detectMultiNodeScript = `%v=""
if [ $(find /sys/devices/system/node/ -maxdepth 1 -mindepth 1 -type d -name node\* | wc -l ) -gt 1 ]
then
%v=" numactl --interleave=all "
# Ensure sysctl turns off zone_reclaim_mode if not already set
(grep -q vm.zone_reclaim_mode /etc/sysctl.conf || echo vm.zone_reclaim_mode = 0 >> /etc/sysctl.conf) && sysctl -p
fi
`
)
// mongoService is a slimmed-down version of the service.Service interface.
type mongoService interface {
Exists() (bool, error)
Installed() (bool, error)
Running() (bool, error)
service.ServiceActions
}
var newService = func(name string, conf common.Conf) (mongoService, error) {
if featureflag.Enabled(feature.MongoDbSnap) {
return snap.NewServiceFromName(name, conf)
}
return service.DiscoverService(name, conf)
}
var discoverService = func(name string) (mongoService, error) {
return newService(name, common.Conf{})
}
// IsServiceInstalled returns whether the MongoDB init service
// configuration is present.
var IsServiceInstalled = isServiceInstalled
func isServiceInstalled() (bool, error) {
svc, err := discoverService(ServiceName)
if err != nil {
return false, errors.Trace(err)
}
return svc.Installed()
}
// RemoveService removes the mongoDB init service from this machine.
func RemoveService() error {
svc, err := discoverService(ServiceName)
if err != nil {
return errors.Trace(err)
}
if err := svc.Stop(); err != nil {
return errors.Trace(err)
}
if err := svc.Remove(); err != nil {
return errors.Trace(err)
}
return nil
}
// StopService will stop mongodb service.
func StopService() error {
svc, err := discoverService(ServiceName)
if err != nil {
return errors.Trace(err)
}
return svc.Stop()
}
// StartService will start mongodb service.
func StartService() error {
svc, err := discoverService(ServiceName)
if err != nil {
return errors.Trace(err)
}
return svc.Start()
}
// ReStartService will stop and then start mongodb service.
func ReStartService() error {
// TODO(tsm): refactor to make use of service.RestartableService
svc, err := discoverService(ServiceName)
if err != nil {
return errors.Trace(err)
}
return restartService(svc)
}
func restartService(svc mongoService) error {
// TODO(tsm): refactor to make use of service.RestartableService
if err := svc.Stop(); err != nil {
return errors.Trace(err)
}
if err := svc.Start(); err != nil {
return errors.Trace(err)
}
return nil
}
func sslKeyPath(dataDir string) string {
return filepath.Join(dataDir, FileNameDBSSLKey)
}
func sharedSecretPath(dataDir string) string {
return filepath.Join(dataDir, SharedSecretFile)
}
func logPath(dataDir string) string {
if featureflag.Enabled(feature.MongoDbSnap) {
return filepath.Join(dataDir, "logs", "mongodb.log")
}
return mongoLogPath
}
func configPath(dataDir string) string {
return filepath.Join(dataDir, "juju-db.config")
}
// ConfigArgs holds the attributes of a service configuration for mongo.
type ConfigArgs struct {
DataDir string
DBDir string
MongoPath string
ReplicaSet string
Version Version
// connection params
BindIP string
BindToAllIP bool
Port int
OplogSizeMB int
// auth
AuthKeyFile string
PEMKeyFile string
PEMKeyPassword string
// network params
IPv6 bool
SSLOnNormalPorts bool
SSLMode string
// logging
Syslog bool
LogAppend bool
LogPath string
// db kernel
WantNUMACtl bool
MemoryProfile MemoryProfile
Journal bool
NoPreAlloc bool
SmallFiles bool
WiredTigerCacheSizeGB float32
// misc
Quiet bool
}
type configArgsConverter map[string]string
func (conf configArgsConverter) asCommandLineArguments() string {
command := make([]string, 0, len(conf)*2)
for key, value := range conf {
if len(key) >= 2 {
key = "--" + key
} else if len(key) == 1 {
key = "-" + key
} else {
continue // impossible?
}
command = append(command, key)
if value == flagMarker {
continue
}
command = append(command, value)
}
return strings.Join(command, " ")
}
func (conf configArgsConverter) asMongoDbConfigurationFileFormat() string {
pathArgs := set.NewStrings("dbpath", "logpath", "sslPEMKeyFile", "keyFile")
command := make([]string, 0, len(conf))
for key, value := range conf {
if len(key) == 0 {
continue
}
if pathArgs.Contains(key) {
value = strings.Trim(value, " '")
}
if value == flagMarker {
value = "true"
}
line := fmt.Sprintf("%s = %s", key, value)
if strings.HasPrefix(key, "sslPEMKeyPassword") {
line = key
}
command = append(command, line)
}
return strings.Join(command, "\n")
}
func (mongoArgs *ConfigArgs) asMap() configArgsConverter {
result := configArgsConverter{}
result["replSet"] = mongoArgs.ReplicaSet
result["dbpath"] = utils.ShQuote(mongoArgs.DBDir)
if mongoArgs.LogPath != "" {
result["logpath"] = utils.ShQuote(mongoArgs.LogPath)
}
if mongoArgs.BindIP != "" {
result["bind_ip"] = mongoArgs.BindIP
}
if mongoArgs.Port != 0 {
result["port"] = strconv.Itoa(mongoArgs.Port)
}
if mongoArgs.IPv6 {
result["ipv6"] = flagMarker
}
if mongoArgs.BindToAllIP {
result["bind_ip_all"] = flagMarker
}
if mongoArgs.SSLMode != "" {
result["sslMode"] = mongoArgs.SSLMode
}
if mongoArgs.LogAppend {
result["logappend"] = flagMarker
}
if mongoArgs.SSLOnNormalPorts {
result["sslOnNormalPorts"] = flagMarker
}
// authn
if mongoArgs.PEMKeyFile != "" {
result["sslPEMKeyFile"] = utils.ShQuote(mongoArgs.PEMKeyFile)
//--sslPEMKeyPassword must be concatenated to the equals sign (lp:1581284)
pemPassword := mongoArgs.PEMKeyPassword
if pemPassword == "" {
pemPassword = "ignored"
}
result["sslPEMKeyPassword="+pemPassword] = flagMarker
}
if mongoArgs.AuthKeyFile != "" {
result["auth"] = flagMarker
result["keyFile"] = utils.ShQuote(mongoArgs.AuthKeyFile)
} else {
logger.Warningf("configuring mongod with --noauth flag enabled")
result["noauth"] = flagMarker
}
// ops config
if mongoArgs.Syslog {
result["syslog"] = flagMarker
}
if mongoArgs.Journal {
result["journal"] = flagMarker
}
if mongoArgs.OplogSizeMB != 0 {
result["oplogSize"] = strconv.Itoa(mongoArgs.OplogSizeMB)
}
if mongoArgs.NoPreAlloc {
result["noprealloc"] = flagMarker
}
if mongoArgs.SmallFiles {
result["smallfiles"] = flagMarker
}
// storageEngine is an unsupported argument for mongo 2.x
if mongoArgs.Version.Major >= 3 && mongoArgs.Version.StorageEngine != "" {
result["storageEngine"] = string(mongoArgs.Version.StorageEngine)
}
if mongoArgs.WiredTigerCacheSizeGB > 0.0 {
result["wiredTigerCacheSizeGB"] = fmt.Sprint(mongoArgs.WiredTigerCacheSizeGB)
}
// misc
if mongoArgs.Quiet {
result["quiet"] = flagMarker
}
return result
}
func (mongoArgs *ConfigArgs) asService() (mongoService, error) {
return newService(ServiceName, mongoArgs.asServiceConf())
}
// asServiceConf returns the init system config for the mongo state service.
func (mongoArgs *ConfigArgs) asServiceConf() common.Conf {
// See https://docs.mongodb.com/manual/reference/ulimit/.
limits := map[string]string{
"fsize": "unlimited", // file size
"cpu": "unlimited", // cpu time
"as": "unlimited", // virtual memory size
"memlock": "unlimited", // locked-in-memory size
"nofile": "64000", // open files
"nproc": "64000", // processes/threads
}
conf := common.Conf{
Desc: "juju state database",
Limit: limits,
Timeout: serviceTimeout,
ExecStart: mongoArgs.startCommand(),
ExtraScript: mongoArgs.extraScript(),
}
return conf
}
func (mongoArgs *ConfigArgs) asMongoDbConfigurationFileFormat() string {
return mongoArgs.asMap().asMongoDbConfigurationFileFormat()
}
func (mongoArgs *ConfigArgs) asCommandLineArguments() string {
return mongoArgs.MongoPath + " " + mongoArgs.asMap().asCommandLineArguments()
}
func (mongoArgs *ConfigArgs) startCommand() string {
if featureflag.Enabled(feature.MongoDbSnap) {
// TODO(tsm): work out how to bridge mongoService and service.Service
// to access the StartCommands method, rather than duplicating code
return snap.Command + " start --enable " + ServiceName
}
cmd := ""
if mongoArgs.WantNUMACtl {
cmd = fmt.Sprintf(numaCtlWrap, multinodeVarName) + " "
}
return cmd + mongoArgs.asCommandLineArguments()
}
func (mongoArgs *ConfigArgs) extraScript() string {
if featureflag.Enabled(feature.MongoDbSnap) {
return ""
}
cmd := ""
if mongoArgs.WantNUMACtl {
cmd = fmt.Sprintf(detectMultiNodeScript, multinodeVarName, multinodeVarName)
}
return cmd
}
func (mongoArgs *ConfigArgs) writeConfig(path string) error {
generatedAt := time.Now().String()
configPrologue := fmt.Sprintf(`
# WARNING
# autogenerated by juju on %v
# manual changes to this file are likely be overwritten
`[1:], generatedAt)
configBody := mongoArgs.asMongoDbConfigurationFileFormat()
config := []byte(configPrologue + configBody)
err := utils.AtomicWriteFile(path, config, 0644)
if err != nil {
return errors.Annotate(err, fmt.Sprintf("writingconfig to %s", path))
}
return nil
}
// newMongoDBArgsWithDefaults returns *mongoDbConfigArgs
// under the assumption that MongoDB 3.4 or later is running.
func generateConfig(mongoPath string, dataDir string, statePort int, oplogSizeMB int, setNUMAControlPolicy bool, version Version, memProfile MemoryProfile) *ConfigArgs {
usingWiredTiger := version.StorageEngine == WiredTiger
usingMongo2 := version.Major == 2
usingMongo4orAbove := version.Major > 3
usingMongo36orAbove := usingMongo4orAbove || (version.Major == 3 && version.Minor >= 6)
usingMongo34orAbove := usingMongo36orAbove || (version.Major == 3 && version.Minor >= 4)
useLowMemory := memProfile == MemoryProfileLow
mongoArgs := &ConfigArgs{
DataDir: dataDir,
DBDir: DbDir(dataDir),
MongoPath: mongoPath,
Port: statePort,
OplogSizeMB: oplogSizeMB,
WantNUMACtl: setNUMAControlPolicy,
Version: version,
IPv6: network.SupportsIPv6(),
MemoryProfile: memProfile,
Syslog: true,
Journal: true,
Quiet: true,
ReplicaSet: ReplicaSetName,
AuthKeyFile: sharedSecretPath(dataDir),
PEMKeyFile: sslKeyPath(dataDir),
PEMKeyPassword: "ignored", // used as boilerplate later
SSLOnNormalPorts: false,
//BindIP: "127.0.0.1", // TODO(tsm): use machine's actual IP address via dialInfo
}
if useLowMemory && usingWiredTiger {
if usingMongo34orAbove {
// Mongo 3.4 introduced the ability to have fractional GB cache size.
mongoArgs.WiredTigerCacheSizeGB = Mongo34LowCacheSize
} else {
mongoArgs.WiredTigerCacheSizeGB = LowCacheSize
}
}
if !usingWiredTiger {
mongoArgs.NoPreAlloc = true
mongoArgs.SmallFiles = true
}
if usingMongo36orAbove {
mongoArgs.BindToAllIP = true
}
if usingMongo2 {
mongoArgs.SSLOnNormalPorts = true
} else {
mongoArgs.SSLMode = "requireSSL"
}
if featureflag.Enabled(feature.MongoDbSnap) {
// Switch from syslog to appending to dataDir, because snaps don't
// have the same permissions.
mongoArgs.Syslog = false
mongoArgs.LogAppend = true
mongoArgs.LogPath = logPath(dataDir)
mongoArgs.BindToAllIP = true // TODO(tsm): disable when not needed
}
return mongoArgs
}
// newConf returns the init system config for the mongo state service.
func newConf(args *ConfigArgs) common.Conf {
return args.asServiceConf()
}
func ensureDirectoriesMade(dataDir string) error {
dbDir := DbDir(dataDir)
if err := os.MkdirAll(dbDir, 0700); err != nil {
return errors.Annotate(err, "cannot create mongo database directory")
}
return nil
}
// EnsureServiceInstalled is a convenience method to [re]create
// the mongo service. It assumes that the necessary packages are
// already installed and that the file system includes secrets at dataDir.
func EnsureServiceInstalled(dataDir string, statePort int, oplogSizeMB int, setNUMAControlPolicy bool, version Version, auth bool, memProfile MemoryProfile) error {
// TODO(tsm): delete EnsureServiceInstalled and use EnsureServer for upgrades
// once upgrade_mongo is removed.
err := ensureDirectoriesMade(dataDir)
if err != nil {
return errors.Trace(err)
}
mongoPath, err := Path(version)
if err != nil {
return errors.NewNotFound(err, "unable to find path to mongod")
}
mongoArgs := generateConfig(
mongoPath,
dataDir,
statePort,
oplogSizeMB,
setNUMAControlPolicy,
version,
memProfile,
)
if !auth {
mongoArgs.AuthKeyFile = ""
}
service, err := mongoArgs.asService()
if err != nil {
return errors.Trace(err)
}
alreadyInstalled, err := service.Installed()
if err != nil {
return errors.Trace(err)
}
if alreadyInstalled {
return nil
}
err = service.Install()
if err != nil {
return errors.Trace(err)
}
return nil
}