-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmachine.go
1060 lines (977 loc) · 33.6 KB
/
machine.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 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package main
import (
"fmt"
"net"
"os"
"path/filepath"
"runtime"
"strconv"
"sync"
"time"
"github.com/juju/cmd"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names"
"github.com/juju/utils"
"github.com/juju/utils/symlink"
"github.com/juju/utils/voyeur"
"gopkg.in/juju/charm.v4"
"gopkg.in/mgo.v2"
"launchpad.net/gnuflag"
"launchpad.net/tomb"
"github.com/juju/juju/agent"
"github.com/juju/juju/api"
apiagent "github.com/juju/juju/api/agent"
"github.com/juju/juju/api/metricsmanager"
"github.com/juju/juju/apiserver"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/container/kvm"
"github.com/juju/juju/environs"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/instance"
jujunames "github.com/juju/juju/juju/names"
"github.com/juju/juju/juju/paths"
"github.com/juju/juju/mongo"
"github.com/juju/juju/network"
"github.com/juju/juju/provider"
"github.com/juju/juju/replicaset"
"github.com/juju/juju/service"
"github.com/juju/juju/service/common"
"github.com/juju/juju/state"
coretools "github.com/juju/juju/tools"
"github.com/juju/juju/version"
"github.com/juju/juju/worker"
"github.com/juju/juju/worker/apiaddressupdater"
"github.com/juju/juju/worker/authenticationworker"
"github.com/juju/juju/worker/charmrevisionworker"
"github.com/juju/juju/worker/cleaner"
"github.com/juju/juju/worker/deployer"
"github.com/juju/juju/worker/firewaller"
"github.com/juju/juju/worker/instancepoller"
"github.com/juju/juju/worker/localstorage"
workerlogger "github.com/juju/juju/worker/logger"
"github.com/juju/juju/worker/machineenvironmentworker"
"github.com/juju/juju/worker/machiner"
"github.com/juju/juju/worker/metricworker"
"github.com/juju/juju/worker/minunitsworker"
"github.com/juju/juju/worker/networker"
"github.com/juju/juju/worker/peergrouper"
"github.com/juju/juju/worker/provisioner"
"github.com/juju/juju/worker/resumer"
"github.com/juju/juju/worker/rsyslog"
"github.com/juju/juju/worker/singular"
"github.com/juju/juju/worker/terminationworker"
"github.com/juju/juju/worker/upgrader"
)
var logger = loggo.GetLogger("juju.cmd.jujud")
var newRunner = worker.NewRunner
const bootstrapMachineId = "0"
// eitherState can be either a *state.State or a *api.State.
type eitherState interface{}
var (
retryDelay = 3 * time.Second
jujuRun = paths.MustSucceed(paths.JujuRun(version.Current.Series))
useMultipleCPUs = utils.UseMultipleCPUs
// The following are defined as variables to
// allow the tests to intercept calls to the functions.
ensureMongoServer = mongo.EnsureServer
maybeInitiateMongoServer = peergrouper.MaybeInitiateMongoServer
ensureMongoAdminUser = mongo.EnsureAdminUser
newSingularRunner = singular.New
peergrouperNew = peergrouper.New
newNetworker = networker.NewNetworker
newFirewaller = firewaller.NewFirewaller
// reportOpenedAPI is exposed for tests to know when
// the State has been successfully opened.
reportOpenedState = func(eitherState) {}
// reportOpenedAPI is exposed for tests to know when
// the API has been successfully opened.
reportOpenedAPI = func(eitherState) {}
getMetricAPI = metricAPI
)
// PrepareRestore will flag the agent to allow only one command:
// Restore, this will ensure that we can do all the file movements
// required for restore and no one will do changes while we do that.
// it will return error if the machine is already in this state.
func (a *MachineAgent) PrepareRestore() error {
if a.restoreMode {
return fmt.Errorf("already in restore mode")
}
a.restoreMode = true
return nil
}
// BeginRestore will flag the agent to disallow all commands since
// restore should be running and therefore making changes that
// would override anything done.
func (a *MachineAgent) BeginRestore() error {
switch {
case !a.restoreMode:
return fmt.Errorf("not in restore mode, cannot begin restoration")
case a.restoring:
return fmt.Errorf("already restoring")
}
a.restoring = true
return nil
}
// FinishRestore will restart jujud and err if restore flag is not true
func (a *MachineAgent) FinishRestore() error {
if !a.restoring {
return fmt.Errorf("restore is not in progress")
}
a.tomb.Kill(worker.ErrTerminateAgent)
return nil
}
// IsRestorePreparing returns bool representing if we are in restore mode
// but not running restore
func (a *MachineAgent) IsRestorePreparing() bool {
return a.restoreMode && !a.restoring
}
func (a *MachineAgent) IsRestoreRunning() bool {
return a.restoring
}
// MachineAgent is a cmd.Command responsible for running a machine agent.
type MachineAgent struct {
cmd.CommandBase
tomb tomb.Tomb
AgentConf
MachineId string
previousAgentVersion version.Number
runner worker.Runner
configChangedVal voyeur.Value
upgradeWorkerContext *upgradeWorkerContext
restoreMode bool
restoring bool
workersStarted chan struct{}
st *state.State
mongoInitMutex sync.Mutex
mongoInitialized bool
}
// Info returns usage information for the command.
func (a *MachineAgent) Info() *cmd.Info {
return &cmd.Info{
Name: "machine",
Purpose: "run a juju machine agent",
}
}
func (a *MachineAgent) SetFlags(f *gnuflag.FlagSet) {
a.AgentConf.AddFlags(f)
f.StringVar(&a.MachineId, "machine-id", "", "id of the machine to run")
}
// Init initializes the command for running.
func (a *MachineAgent) Init(args []string) error {
if !names.IsValidMachine(a.MachineId) {
return fmt.Errorf("--machine-id option must be set, and expects a non-negative integer")
}
if err := a.AgentConf.CheckArgs(args); err != nil {
return err
}
a.runner = newRunner(isFatal, moreImportant)
a.workersStarted = make(chan struct{})
a.upgradeWorkerContext = NewUpgradeWorkerContext()
return nil
}
// Wait waits for the machine agent to finish.
func (a *MachineAgent) Wait() error {
return a.tomb.Wait()
}
// Stop stops the machine agent.
func (a *MachineAgent) Stop() error {
a.runner.Kill()
return a.tomb.Wait()
}
// Dying returns the channel that can be used to see if the machine
// agent is terminating.
func (a *MachineAgent) Dying() <-chan struct{} {
return a.tomb.Dying()
}
// Run runs a machine agent.
func (a *MachineAgent) Run(_ *cmd.Context) error {
// Due to changes in the logging, and needing to care about old
// environments that have been upgraded, we need to explicitly remove the
// file writer if one has been added, otherwise we will get duplicate
// lines of all logging in the log file.
loggo.RemoveWriter("logfile")
defer a.tomb.Done()
if err := a.ReadConfig(a.Tag().String()); err != nil {
return fmt.Errorf("cannot read agent configuration: %v", err)
}
agentConfig := a.CurrentConfig()
if err := setupLogging(agentConfig); err != nil {
return err
}
logger.Infof("machine agent %v start (%s [%s])", a.Tag(), version.Current, runtime.Compiler)
if err := a.upgradeWorkerContext.InitializeUsingAgent(a); err != nil {
return errors.Annotate(err, "error during upgradeWorkerContext initialisation")
}
a.configChangedVal.Set(struct{}{})
a.previousAgentVersion = agentConfig.UpgradedToVersion()
network.InitializeFromConfig(agentConfig)
charm.CacheDir = filepath.Join(agentConfig.DataDir(), "charmcache")
if err := a.createJujuRun(agentConfig.DataDir()); err != nil {
return fmt.Errorf("cannot create juju run symlink: %v", err)
}
a.runner.StartWorker("api", a.APIWorker)
a.runner.StartWorker("statestarter", a.newStateStarterWorker)
a.runner.StartWorker("termination", func() (worker.Worker, error) {
return terminationworker.NewWorker(), nil
})
// At this point, all workers will have been configured to start
close(a.workersStarted)
err := a.runner.Wait()
if err == worker.ErrTerminateAgent {
err = a.uninstallAgent(agentConfig)
}
err = agentDone(err)
a.tomb.Kill(err)
return err
}
func (a *MachineAgent) ChangeConfig(mutate AgentConfigMutator) error {
err := a.AgentConf.ChangeConfig(mutate)
a.configChangedVal.Set(struct{}{})
if err != nil {
return errors.Trace(err)
}
return nil
}
// newStateStarterWorker wraps stateStarter in a simple worker for use in
// a.runner.StartWorker.
func (a *MachineAgent) newStateStarterWorker() (worker.Worker, error) {
return worker.NewSimpleWorker(a.stateStarter), nil
}
// stateStarter watches for changes to the agent configuration, and
// starts or stops the state worker as appropriate. We watch the agent
// configuration because the agent configuration has all the details
// that we need to start a state server, whether they have been cached
// or read from the state.
//
// It will stop working as soon as stopch is closed.
func (a *MachineAgent) stateStarter(stopch <-chan struct{}) error {
confWatch := a.configChangedVal.Watch()
defer confWatch.Close()
watchCh := make(chan struct{})
go func() {
for confWatch.Next() {
watchCh <- struct{}{}
}
}()
for {
select {
case <-watchCh:
agentConfig := a.CurrentConfig()
// N.B. StartWorker and StopWorker are idempotent.
_, ok := agentConfig.StateServingInfo()
if ok {
a.runner.StartWorker("state", func() (worker.Worker, error) {
return a.StateWorker()
})
} else {
a.runner.StopWorker("state")
}
case <-stopch:
return nil
}
}
}
// APIWorker returns a Worker that connects to the API and starts any
// workers that need an API connection.
func (a *MachineAgent) APIWorker() (worker.Worker, error) {
agentConfig := a.CurrentConfig()
st, entity, err := openAPIState(agentConfig, a)
if err != nil {
return nil, err
}
reportOpenedAPI(st)
// Check if the network management is disabled.
envConfig, err := st.Environment().EnvironConfig()
if err != nil {
return nil, fmt.Errorf("cannot read environment config: %v", err)
}
disableNetworkManagement, _ := envConfig.DisableNetworkManagement()
if disableNetworkManagement {
logger.Infof("network management is disabled")
}
// Check if firewall-mode is "none" to disable the firewaller.
firewallMode := envConfig.FirewallMode()
disableFirewaller := firewallMode == config.FwNone
// Refresh the configuration, since it may have been updated after opening state.
agentConfig = a.CurrentConfig()
for _, job := range entity.Jobs() {
if job.NeedsState() {
info, err := st.Agent().StateServingInfo()
if err != nil {
return nil, fmt.Errorf("cannot get state serving info: %v", err)
}
err = a.ChangeConfig(func(config agent.ConfigSetter) error {
config.SetStateServingInfo(info)
return nil
})
if err != nil {
return nil, err
}
agentConfig = a.CurrentConfig()
break
}
}
rsyslogMode := rsyslog.RsyslogModeForwarding
runner := newRunner(connectionIsFatal(st), moreImportant)
var singularRunner worker.Runner
for _, job := range entity.Jobs() {
if job == params.JobManageEnviron {
rsyslogMode = rsyslog.RsyslogModeAccumulate
conn := singularAPIConn{st, st.Agent()}
singularRunner, err = newSingularRunner(runner, conn)
if err != nil {
return nil, fmt.Errorf("cannot make singular API Runner: %v", err)
}
break
}
}
// Before starting any workers, ensure we record the Juju version this machine
// agent is running.
currentTools := &coretools.Tools{Version: version.Current}
if err := st.Upgrader().SetVersion(agentConfig.Tag().String(), currentTools.Version); err != nil {
return nil, errors.Annotate(err, "cannot set machine agent version")
}
providerType := agentConfig.Value(agent.ProviderType)
// Run the upgrader and the upgrade-steps worker without waiting for
// the upgrade steps to complete.
runner.StartWorker("upgrader", func() (worker.Worker, error) {
return upgrader.NewUpgrader(
st.Upgrader(),
agentConfig,
a.previousAgentVersion,
a.upgradeWorkerContext.IsUpgradeRunning,
), nil
})
runner.StartWorker("upgrade-steps", func() (worker.Worker, error) {
return a.upgradeWorkerContext.Worker(a, st, entity.Jobs()), nil
})
// All other workers must wait for the upgrade steps to complete
// before starting.
a.startWorkerAfterUpgrade(runner, "machiner", func() (worker.Worker, error) {
return machiner.NewMachiner(st.Machiner(), agentConfig), nil
})
a.startWorkerAfterUpgrade(runner, "apiaddressupdater", func() (worker.Worker, error) {
return apiaddressupdater.NewAPIAddressUpdater(st.Machiner(), a), nil
})
a.startWorkerAfterUpgrade(runner, "logger", func() (worker.Worker, error) {
return workerlogger.NewLogger(st.Logger(), agentConfig), nil
})
a.startWorkerAfterUpgrade(runner, "machineenvironmentworker", func() (worker.Worker, error) {
return machineenvironmentworker.NewMachineEnvironmentWorker(st.Environment(), agentConfig), nil
})
a.startWorkerAfterUpgrade(runner, "rsyslog", func() (worker.Worker, error) {
return newRsyslogConfigWorker(st.Rsyslog(), agentConfig, rsyslogMode)
})
// Start networker depending on configuration and job.
intrusiveMode := false
for _, job := range entity.Jobs() {
if job == params.JobManageNetworking {
intrusiveMode = true
break
}
}
intrusiveMode = intrusiveMode && !disableNetworkManagement
a.startWorkerAfterUpgrade(runner, "networker", func() (worker.Worker, error) {
return newNetworker(st.Networker(), agentConfig, intrusiveMode, networker.DefaultConfigBaseDir)
})
// If not a local provider bootstrap machine, start the worker to
// manage SSH keys.
if providerType != provider.Local || a.MachineId != bootstrapMachineId {
a.startWorkerAfterUpgrade(runner, "authenticationworker", func() (worker.Worker, error) {
return authenticationworker.NewWorker(st.KeyUpdater(), agentConfig), nil
})
}
// Perform the operations needed to set up hosting for containers.
if err := a.setupContainerSupport(runner, st, entity, agentConfig); err != nil {
cause := errors.Cause(err)
if params.IsCodeDead(cause) || cause == worker.ErrTerminateAgent {
return nil, worker.ErrTerminateAgent
}
return nil, fmt.Errorf("setting up container support: %v", err)
}
for _, job := range entity.Jobs() {
switch job {
case params.JobHostUnits:
a.startWorkerAfterUpgrade(runner, "deployer", func() (worker.Worker, error) {
apiDeployer := st.Deployer()
context := newDeployContext(apiDeployer, agentConfig)
return deployer.NewDeployer(apiDeployer, context), nil
})
case params.JobManageEnviron:
a.startWorkerAfterUpgrade(singularRunner, "environ-provisioner", func() (worker.Worker, error) {
return provisioner.NewEnvironProvisioner(st.Provisioner(), agentConfig), nil
})
// TODO(axw) 2013-09-24 bug #1229506
// Make another job to enable the firewaller. Not all
// environments are capable of managing ports
// centrally.
if !disableFirewaller {
a.startWorkerAfterUpgrade(singularRunner, "firewaller", func() (worker.Worker, error) {
return newFirewaller(st.Firewaller())
})
} else {
logger.Debugf("not starting firewaller worker - firewall-mode is %q", config.FwNone)
}
a.startWorkerAfterUpgrade(singularRunner, "charm-revision-updater", func() (worker.Worker, error) {
return charmrevisionworker.NewRevisionUpdateWorker(st.CharmRevisionUpdater()), nil
})
logger.Infof("starting metric workers")
a.startWorkerAfterUpgrade(runner, "metriccleanupworker", func() (worker.Worker, error) {
return metricworker.NewCleanup(getMetricAPI(st)), nil
})
a.startWorkerAfterUpgrade(runner, "metricsenderworker", func() (worker.Worker, error) {
return metricworker.NewSender(getMetricAPI(st)), nil
})
case params.JobManageStateDeprecated:
// Legacy environments may set this, but we ignore it.
default:
// TODO(dimitern): Once all workers moved over to using
// the API, report "unknown job type" here.
}
}
return newCloseWorker(runner, st), nil // Note: a worker.Runner is itself a worker.Worker.
}
// setupContainerSupport determines what containers can be run on this machine and
// initialises suitable infrastructure to support such containers.
func (a *MachineAgent) setupContainerSupport(runner worker.Runner, st *api.State, entity *apiagent.Entity, agentConfig agent.Config) error {
var supportedContainers []instance.ContainerType
// We don't yet support nested lxc containers but anything else can run an LXC container.
if entity.ContainerType() != instance.LXC {
supportedContainers = append(supportedContainers, instance.LXC)
}
supportsKvm, err := kvm.IsKVMSupported()
if err != nil {
logger.Warningf("determining kvm support: %v\nno kvm containers possible", err)
}
if err == nil && supportsKvm {
supportedContainers = append(supportedContainers, instance.KVM)
}
return a.updateSupportedContainers(runner, st, entity.Tag(), supportedContainers, agentConfig)
}
// updateSupportedContainers records in state that a machine can run the specified containers.
// It starts a watcher and when a container of a given type is first added to the machine,
// the watcher is killed, the machine is set up to be able to start containers of the given type,
// and a suitable provisioner is started.
func (a *MachineAgent) updateSupportedContainers(
runner worker.Runner,
st *api.State,
machineTag string,
containers []instance.ContainerType,
agentConfig agent.Config,
) error {
pr := st.Provisioner()
tag, err := names.ParseMachineTag(machineTag)
if err != nil {
return err
}
machine, err := pr.Machine(tag)
if errors.IsNotFound(err) || err == nil && machine.Life() == params.Dead {
return worker.ErrTerminateAgent
}
if err != nil {
return errors.Annotatef(err, "cannot load machine %s from state", tag)
}
if len(containers) == 0 {
if err := machine.SupportsNoContainers(); err != nil {
return errors.Annotatef(err, "clearing supported containers for %s", tag)
}
return nil
}
if err := machine.SetSupportedContainers(containers...); err != nil {
return errors.Annotatef(err, "setting supported containers for %s", tag)
}
initLock, err := hookExecutionLock(agentConfig.DataDir())
if err != nil {
return err
}
// Start the watcher to fire when a container is first requested on the machine.
watcherName := fmt.Sprintf("%s-container-watcher", machine.Id())
handler := provisioner.NewContainerSetupHandler(
runner,
watcherName,
containers,
machine,
pr,
agentConfig,
initLock,
)
a.startWorkerAfterUpgrade(runner, watcherName, func() (worker.Worker, error) {
return worker.NewStringsWorker(handler), nil
})
return nil
}
// StateWorker returns a worker running all the workers that require
// a *state.State connection.
func (a *MachineAgent) StateWorker() (worker.Worker, error) {
agentConfig := a.CurrentConfig()
// Create system-identity file.
if err := agent.WriteSystemIdentityFile(agentConfig); err != nil {
return nil, err
}
// Start MongoDB server and dial.
if err := a.ensureMongoServer(agentConfig); err != nil {
return nil, err
}
st, m, err := openState(agentConfig, stateWorkerDialOpts)
if err != nil {
return nil, err
}
reportOpenedState(st)
registerSimplestreamsDataSource(st.Storage())
singularStateConn := singularStateConn{st.MongoSession(), m}
runner := newRunner(connectionIsFatal(st), moreImportant)
singularRunner, err := newSingularRunner(runner, singularStateConn)
if err != nil {
return nil, fmt.Errorf("cannot make singular State Runner: %v", err)
}
// Take advantage of special knowledge here in that we will only ever want
// the storage provider on one machine, and that is the "bootstrap" node.
providerType := agentConfig.Value(agent.ProviderType)
if (providerType == provider.Local || provider.IsManual(providerType)) && m.Id() == bootstrapMachineId {
a.startWorkerAfterUpgrade(runner, "local-storage", func() (worker.Worker, error) {
// TODO(axw) 2013-09-24 bug #1229507
// Make another job to enable storage.
// There's nothing special about this.
return localstorage.NewWorker(agentConfig), nil
})
}
for _, job := range m.Jobs() {
switch job {
case state.JobHostUnits:
// Implemented in APIWorker.
case state.JobManageEnviron:
useMultipleCPUs()
a.startWorkerAfterUpgrade(runner, "instancepoller", func() (worker.Worker, error) {
return instancepoller.NewWorker(st), nil
})
a.startWorkerAfterUpgrade(runner, "peergrouper", func() (worker.Worker, error) {
return peergrouperNew(st)
})
runner.StartWorker("apiserver", func() (worker.Worker, error) {
// If the configuration does not have the required information,
// it is currently not a recoverable error, so we kill the whole
// agent, potentially enabling human intervention to fix
// the agent's configuration file. In the future, we may retrieve
// the state server certificate and key from the state, and
// this should then change.
info, ok := agentConfig.StateServingInfo()
if !ok {
return nil, &fatalError{"StateServingInfo not available and we need it"}
}
cert := []byte(info.Cert)
key := []byte(info.PrivateKey)
if len(cert) == 0 || len(key) == 0 {
return nil, &fatalError{"configuration does not have state server cert/key"}
}
dataDir := agentConfig.DataDir()
logDir := agentConfig.LogDir()
endpoint := net.JoinHostPort("", strconv.Itoa(info.APIPort))
listener, err := net.Listen("tcp", endpoint)
if err != nil {
return nil, err
}
return apiserver.NewServer(st, listener, apiserver.ServerConfig{
Cert: cert,
Key: key,
DataDir: dataDir,
LogDir: logDir,
Validator: a.limitLoginsDuringUpgrade,
})
})
a.startWorkerAfterUpgrade(singularRunner, "cleaner", func() (worker.Worker, error) {
return cleaner.NewCleaner(st), nil
})
a.startWorkerAfterUpgrade(singularRunner, "resumer", func() (worker.Worker, error) {
// The action of resumer is so subtle that it is not tested,
// because we can't figure out how to do so without brutalising
// the transaction log.
return resumer.NewResumer(st), nil
})
a.startWorkerAfterUpgrade(singularRunner, "minunitsworker", func() (worker.Worker, error) {
return minunitsworker.NewMinUnitsWorker(st), nil
})
case state.JobManageStateDeprecated:
// Legacy environments may set this, but we ignore it.
default:
logger.Warningf("ignoring unknown job %q", job)
}
}
return newCloseWorker(runner, st), nil
}
// stateWorkerDialOpts is a mongo.DialOpts suitable
// for use by StateWorker to dial mongo.
//
// This must be overridden in tests, as it assumes
// journaling is enabled.
var stateWorkerDialOpts mongo.DialOpts
func init() {
stateWorkerDialOpts = mongo.DefaultDialOpts()
stateWorkerDialOpts.PostDial = func(session *mgo.Session) error {
safe := mgo.Safe{
// Wait for group commit if journaling is enabled,
// which is always true in production.
J: true,
}
_, err := replicaset.CurrentConfig(session)
if err == nil {
// set mongo to write-majority (writes only returned after
// replicated to a majority of replica-set members).
safe.WMode = "majority"
}
session.SetSafe(&safe)
return nil
}
}
// limitLogin is called by the API server for each login attempt.
// it returns an error if upgrads or restore are running.
func (a *MachineAgent) limitLogins(req params.LoginRequest) error {
err := a.limitLoginsDuringRestore(req)
if err != nil {
return err
}
err = a.limitLoginsDuringUpgrade(req)
if err != nil {
return err
}
return nil
}
func (a *MachineAgent) limitLoginsDuringRestore(req params.LoginRequest) error {
var err error
switch {
case a.IsRestoreRunning():
err = apiserver.RestoreInProgressError
case a.IsRestorePreparing():
err = apiserver.AboutToRestoreError
}
if err != nil {
authTag, parseErr := names.ParseTag(req.AuthTag)
if parseErr != nil {
return errors.Annotate(err, "could not parse auth tag")
}
switch authTag := authTag.(type) {
case names.UserTag:
// use a restricted API mode
return err
case names.MachineTag:
if authTag == a.Tag() {
// allow logins from the local machine
return nil
}
}
return errors.Errorf("login for %q blocked because restore is in progress", authTag)
}
return nil
}
// limitLoginsDuringUpgrade is called by the API server for each login
// attempt. It returns an error if upgrades are in progress unless the
// login is for a user (i.e. a client) or the local machine.
func (a *MachineAgent) limitLoginsDuringUpgrade(req params.LoginRequest) error {
if a.upgradeWorkerContext.IsUpgradeRunning() {
authTag, err := names.ParseTag(req.AuthTag)
if err != nil {
return errors.Annotate(err, "could not parse auth tag")
}
switch authTag := authTag.(type) {
case names.UserTag:
// use a restricted API mode
return apiserver.UpgradeInProgressError
case names.MachineTag:
if authTag == a.Tag() {
// allow logins from the local machine
return nil
}
}
return errors.Errorf("login for %q blocked because upgrade is in progress", authTag)
} else {
return nil // allow all logins
}
}
// ensureMongoServer ensures that mongo is installed and running,
// and ready for opening a state connection.
func (a *MachineAgent) ensureMongoServer(agentConfig agent.Config) (err error) {
a.mongoInitMutex.Lock()
defer a.mongoInitMutex.Unlock()
if a.mongoInitialized {
logger.Debugf("mongo is already initialized")
return nil
}
defer func() {
if err == nil {
a.mongoInitialized = true
}
}()
servingInfo, ok := agentConfig.StateServingInfo()
if !ok {
return fmt.Errorf("state worker was started with no state serving info")
}
// When upgrading from a pre-HA-capable environment,
// we must add machine-0 to the admin database and
// initiate its replicaset.
//
// TODO(axw) remove this when we no longer need
// to upgrade from pre-HA-capable environments.
var shouldInitiateMongoServer bool
var addrs []network.Address
if isPreHAVersion(a.previousAgentVersion) {
_, err := a.ensureMongoAdminUser(agentConfig)
if err != nil {
return err
}
if servingInfo.SharedSecret == "" {
servingInfo.SharedSecret, err = mongo.GenerateSharedSecret()
if err != nil {
return err
}
if err = a.ChangeConfig(func(config agent.ConfigSetter) error {
config.SetStateServingInfo(servingInfo)
return nil
}); err != nil {
return err
}
agentConfig = a.CurrentConfig()
}
// Note: we set Direct=true in the mongo options because it's
// possible that we've previously upgraded the mongo server's
// configuration to form a replicaset, but failed to initiate it.
st, m, err := openState(agentConfig, mongo.DialOpts{Direct: true})
if err != nil {
return err
}
ssi := paramsStateServingInfoToStateStateServingInfo(servingInfo)
if err := st.SetStateServingInfo(ssi); err != nil {
st.Close()
return fmt.Errorf("cannot set state serving info: %v", err)
}
st.Close()
addrs = m.Addresses()
shouldInitiateMongoServer = true
}
// ensureMongoServer installs/upgrades the upstart config as necessary.
ensureServerParams, err := newEnsureServerParams(agentConfig)
if err != nil {
return err
}
if err := ensureMongoServer(ensureServerParams); err != nil {
return err
}
if !shouldInitiateMongoServer {
return nil
}
// Initiate the replicaset for upgraded environments.
//
// TODO(axw) remove this when we no longer need
// to upgrade from pre-HA-capable environments.
stateInfo, ok := agentConfig.MongoInfo()
if !ok {
return fmt.Errorf("state worker was started with no state serving info")
}
dialInfo, err := mongo.DialInfo(stateInfo.Info, mongo.DefaultDialOpts())
if err != nil {
return err
}
peerAddr := mongo.SelectPeerAddress(addrs)
if peerAddr == "" {
return fmt.Errorf("no appropriate peer address found in %q", addrs)
}
if err := maybeInitiateMongoServer(peergrouper.InitiateMongoParams{
DialInfo: dialInfo,
MemberHostPort: net.JoinHostPort(peerAddr, fmt.Sprint(servingInfo.StatePort)),
// TODO(dfc) InitiateMongoParams should take a Tag
User: stateInfo.Tag.String(),
Password: stateInfo.Password,
}); err != nil {
return err
}
return nil
}
func paramsStateServingInfoToStateStateServingInfo(i params.StateServingInfo) state.StateServingInfo {
return state.StateServingInfo{
APIPort: i.APIPort,
StatePort: i.StatePort,
Cert: i.Cert,
PrivateKey: i.PrivateKey,
SharedSecret: i.SharedSecret,
SystemIdentity: i.SystemIdentity,
}
}
func (a *MachineAgent) ensureMongoAdminUser(agentConfig agent.Config) (added bool, err error) {
stateInfo, ok1 := agentConfig.MongoInfo()
servingInfo, ok2 := agentConfig.StateServingInfo()
if !ok1 || !ok2 {
return false, fmt.Errorf("no state serving info configuration")
}
dialInfo, err := mongo.DialInfo(stateInfo.Info, mongo.DefaultDialOpts())
if err != nil {
return false, err
}
if len(dialInfo.Addrs) > 1 {
logger.Infof("more than one state server; admin user must exist")
return false, nil
}
return ensureMongoAdminUser(mongo.EnsureAdminUserParams{
DialInfo: dialInfo,
Namespace: agentConfig.Value(agent.Namespace),
DataDir: agentConfig.DataDir(),
Port: servingInfo.StatePort,
User: stateInfo.Tag.String(),
Password: stateInfo.Password,
})
}
func isPreHAVersion(v version.Number) bool {
return v.Compare(version.MustParse("1.19.0")) < 0
}
func openState(agentConfig agent.Config, dialOpts mongo.DialOpts) (_ *state.State, _ *state.Machine, err error) {
info, ok := agentConfig.MongoInfo()
if !ok {
return nil, nil, fmt.Errorf("no state info available")
}
st, err := state.Open(info, dialOpts, environs.NewStatePolicy())
if err != nil {
return nil, nil, err
}
defer func() {
if err != nil {
st.Close()
}
}()
m0, err := st.FindEntity(agentConfig.Tag())
if err != nil {
if errors.IsNotFound(err) {
err = worker.ErrTerminateAgent
}
return nil, nil, err
}
m := m0.(*state.Machine)
if m.Life() == state.Dead {
return nil, nil, worker.ErrTerminateAgent
}
// Check the machine nonce as provisioned matches the agent.Conf value.
if !m.CheckProvisioned(agentConfig.Nonce()) {
// The agent is running on a different machine to the one it
// should be according to state. It must stop immediately.
logger.Errorf("running machine %v agent on inappropriate instance", m)
return nil, nil, worker.ErrTerminateAgent
}
return st, m, nil
}
// startWorkerAfterUpgrade starts a worker to run the specified child worker
// but only after waiting for upgrades to complete.
func (a *MachineAgent) startWorkerAfterUpgrade(runner worker.Runner, name string, start func() (worker.Worker, error)) {
runner.StartWorker(name, func() (worker.Worker, error) {
return a.upgradeWaiterWorker(start), nil
})
}
// upgradeWaiterWorker runs the specified worker after upgrades have completed.
func (a *MachineAgent) upgradeWaiterWorker(start func() (worker.Worker, error)) worker.Worker {
return worker.NewSimpleWorker(func(stop <-chan struct{}) error {
// Wait for the upgrade to complete (or for us to be stopped).
select {
case <-stop:
return nil
case <-a.upgradeWorkerContext.UpgradeComplete:
}
// Upgrades are done, start the worker.
worker, err := start()
if err != nil {
return err
}
// Wait for worker to finish or for us to be stopped.
waitCh := make(chan error)
go func() {
waitCh <- worker.Wait()
}()
select {
case err := <-waitCh:
return err
case <-stop:
worker.Kill()
}
return <-waitCh // Ensure worker has stopped before returning.
})
}
func (a *MachineAgent) setMachineStatus(apiState *api.State, status params.Status, info string) error {
tag := a.Tag().(names.MachineTag)
machine, err := apiState.Machiner().Machine(tag)
if err != nil {
return errors.Trace(err)
}
if err := machine.SetStatus(status, info, nil); err != nil {
return errors.Trace(err)
}
return nil
}
// WorkersStarted returns a channel that's closed once all top level workers
// have been started. This is provided for testing purposes.
func (a *MachineAgent) WorkersStarted() <-chan struct{} {
return a.workersStarted
}
func (a *MachineAgent) Tag() names.Tag {
return names.NewMachineTag(a.MachineId)
}
func (a *MachineAgent) createJujuRun(dataDir string) error {
// TODO do not remove the symlink if it already points
// to the right place.
if err := os.Remove(jujuRun); err != nil && !os.IsNotExist(err) {
return err
}
jujud := filepath.Join(dataDir, "tools", a.Tag().String(), jujunames.Jujud)
return symlink.New(jujud, jujuRun)
}
func (a *MachineAgent) uninstallAgent(agentConfig agent.Config) error {
var errors []error
agentServiceName := agentConfig.Value(agent.AgentServiceName)