-
Notifications
You must be signed in to change notification settings - Fork 0
/
manifold.go
104 lines (92 loc) · 2.61 KB
/
manifold.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
// Copyright 2015-2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package singular
import (
"time"
"github.com/juju/clock"
"github.com/juju/errors"
"gopkg.in/juju/names.v2"
"gopkg.in/juju/worker.v1"
"gopkg.in/juju/worker.v1/dependency"
"github.com/juju/juju/api/base"
"github.com/juju/juju/cmd/jujud/agent/engine"
)
// ManifoldConfig holds the information necessary to run a FlagWorker in
// a dependency.Engine.
type ManifoldConfig struct {
Clock clock.Clock
APICallerName string
Duration time.Duration
Claimant names.MachineTag
Entity names.Tag
NewFacade func(base.APICaller, names.MachineTag, names.Tag) (Facade, error)
NewWorker func(FlagConfig) (worker.Worker, error)
}
// Validate ensures the required values are set.
func (config *ManifoldConfig) Validate() error {
if config.Clock == nil {
return errors.NotValidf("nil Clock")
}
if config.APICallerName == "" {
return errors.NotValidf("missing APICallerName")
}
if config.NewFacade == nil {
return errors.NotValidf("nil NewFacade")
}
if config.NewWorker == nil {
return errors.NotValidf("nil NewWorker")
}
return nil
}
// start is a method on ManifoldConfig because it's more readable than a closure.
func (config ManifoldConfig) start(context dependency.Context) (worker.Worker, error) {
if err := config.Validate(); err != nil {
return nil, errors.Trace(err)
}
var apiCaller base.APICaller
if err := context.Get(config.APICallerName, &apiCaller); err != nil {
return nil, errors.Trace(err)
}
facade, err := config.NewFacade(apiCaller, config.Claimant, config.Entity)
if err != nil {
return nil, errors.Trace(err)
}
flag, err := config.NewWorker(FlagConfig{
Clock: config.Clock,
Facade: facade,
Duration: config.Duration,
})
if err != nil {
return nil, errors.Trace(err)
}
return wrappedWorker{flag}, nil
}
// wrappedWorker wraps a flag worker, translating ErrRefresh into
// dependency.ErrBounce.
type wrappedWorker struct {
worker.Worker
}
// Wait is part of the worker.Worker interface.
func (w wrappedWorker) Wait() error {
err := w.Worker.Wait()
if err == ErrRefresh {
err = dependency.ErrBounce
}
return err
}
// Manifold returns a dependency.Manifold that will run a FlagWorker and
// expose it to clients as a engine.Flag resource.
func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{
config.APICallerName,
},
Start: config.start,
Output: func(in worker.Worker, out interface{}) error {
if w, ok := in.(wrappedWorker); ok {
in = w.Worker
}
return engine.FlagOutput(in, out)
},
}
}