-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloudinit.go
283 lines (264 loc) · 9.46 KB
/
cloudinit.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
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package environs
import (
"fmt"
"path"
"strconv"
"github.com/juju/errors"
"github.com/juju/names"
"github.com/juju/utils"
"github.com/juju/utils/proxy"
"github.com/juju/juju/agent"
"github.com/juju/juju/api"
"github.com/juju/juju/apiserver/params"
coreCloudinit "github.com/juju/juju/cloudinit"
"github.com/juju/juju/constraints"
"github.com/juju/juju/environs/cloudinit"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/juju/paths"
"github.com/juju/juju/mongo"
"github.com/juju/juju/state/multiwatcher"
"github.com/juju/juju/version"
)
// DataDir is the default data directory. Tests can override this
// where needed, so they don't need to mess with global system state.
var DataDir = agent.DefaultDataDir
// logDir returns a filesystem path to the location where applications
// may create a folder containing logs
var logDir = paths.MustSucceed(paths.LogDir(version.Current.Series))
// DefaultBridgeName is the network bridge device name used for LXC
// and KVM containers.
const DefaultBridgeName = "juju-br0"
// NewMachineConfig sets up a basic machine configuration, for a
// non-bootstrap node. You'll still need to supply more information,
// but this takes care of the fixed entries and the ones that are
// always needed.
func NewMachineConfig(
machineID,
machineNonce,
imageStream,
series string,
secureServerConnections bool,
networks []string,
mongoInfo *mongo.MongoInfo,
apiInfo *api.Info,
) (*cloudinit.MachineConfig, error) {
dataDir, err := paths.DataDir(series)
if err != nil {
return nil, err
}
logDir, err := paths.LogDir(series)
if err != nil {
return nil, err
}
cloudInitOutputLog := path.Join(logDir, "cloud-init-output.log")
mcfg := &cloudinit.MachineConfig{
// Fixed entries.
DataDir: dataDir,
LogDir: path.Join(logDir, "juju"),
Jobs: []multiwatcher.MachineJob{multiwatcher.JobHostUnits},
CloudInitOutputLog: cloudInitOutputLog,
MachineAgentServiceName: "jujud-" + names.NewMachineTag(machineID).String(),
Series: series,
// Parameter entries.
MachineId: machineID,
MachineNonce: machineNonce,
Networks: networks,
MongoInfo: mongoInfo,
APIInfo: apiInfo,
ImageStream: imageStream,
AgentEnvironment: map[string]string{
agent.AllowsSecureConnection: strconv.FormatBool(secureServerConnections),
},
}
return mcfg, nil
}
// NewBootstrapMachineConfig sets up a basic machine configuration for a
// bootstrap node. You'll still need to supply more information, but this
// takes care of the fixed entries and the ones that are always needed.
func NewBootstrapMachineConfig(cons constraints.Value, series string) (*cloudinit.MachineConfig, error) {
// For a bootstrap instance, FinishMachineConfig will provide the
// state.Info and the api.Info. The machine id must *always* be "0".
mcfg, err := NewMachineConfig("0", agent.BootstrapNonce, "", series, true, nil, nil, nil)
if err != nil {
return nil, err
}
mcfg.Bootstrap = true
mcfg.Jobs = []multiwatcher.MachineJob{
multiwatcher.JobManageEnviron,
multiwatcher.JobHostUnits,
}
mcfg.Constraints = cons
return mcfg, nil
}
// PopulateMachineConfig is called both from the FinishMachineConfig below,
// which does have access to the environment config, and from the container
// provisioners, which don't have access to the environment config. Everything
// that is needed to provision a container needs to be returned to the
// provisioner in the ContainerConfig structure. Those values are then used to
// call this function.
func PopulateMachineConfig(mcfg *cloudinit.MachineConfig,
providerType, authorizedKeys string,
sslHostnameVerification bool,
proxySettings, aptProxySettings proxy.Settings,
aptMirror string,
preferIPv6 bool,
enableOSRefreshUpdates bool,
enableOSUpgrade bool,
) error {
if authorizedKeys == "" {
return fmt.Errorf("environment configuration has no authorized-keys")
}
mcfg.AuthorizedKeys = authorizedKeys
if mcfg.AgentEnvironment == nil {
mcfg.AgentEnvironment = make(map[string]string)
}
mcfg.AgentEnvironment[agent.ProviderType] = providerType
mcfg.AgentEnvironment[agent.ContainerType] = string(mcfg.MachineContainerType)
mcfg.DisableSSLHostnameVerification = !sslHostnameVerification
mcfg.ProxySettings = proxySettings
mcfg.AptProxySettings = aptProxySettings
mcfg.AptMirror = aptMirror
mcfg.PreferIPv6 = preferIPv6
mcfg.EnableOSRefreshUpdate = enableOSRefreshUpdates
mcfg.EnableOSUpgrade = enableOSUpgrade
return nil
}
// FinishMachineConfig sets fields on a MachineConfig that can be determined by
// inspecting a plain config.Config and the machine constraints at the last
// moment before bootstrapping. It assumes that the supplied Config comes from
// an environment that has passed through all the validation checks in the
// Bootstrap func, and that has set an agent-version (via finding the tools to,
// use for bootstrap, or otherwise).
// TODO(fwereade) This function is not meant to be "good" in any serious way:
// it is better that this functionality be collected in one place here than
// that it be spread out across 3 or 4 providers, but this is its only
// redeeming feature.
func FinishMachineConfig(mcfg *cloudinit.MachineConfig, cfg *config.Config) (err error) {
defer errors.DeferredAnnotatef(&err, "cannot complete machine configuration")
if err := PopulateMachineConfig(
mcfg,
cfg.Type(),
cfg.AuthorizedKeys(),
cfg.SSLHostnameVerification(),
cfg.ProxySettings(),
cfg.AptProxySettings(),
cfg.AptMirror(),
cfg.PreferIPv6(),
cfg.EnableOSRefreshUpdate(),
cfg.EnableOSUpgrade(),
); err != nil {
return errors.Trace(err)
}
if isStateMachineConfig(mcfg) {
// Add NUMACTL preference. Needed to work for both bootstrap and high availability
// Only makes sense for state server
logger.Debugf("Setting numa ctl preference to %v", cfg.NumaCtlPreference())
// Unfortunately, AgentEnvironment can only take strings as values
mcfg.AgentEnvironment[agent.NumaCtlPreference] = fmt.Sprintf("%v", cfg.NumaCtlPreference())
}
// The following settings are only appropriate at bootstrap time. At the
// moment, the only state server is the bootstrap node, but this
// will probably change.
if !mcfg.Bootstrap {
return nil
}
if mcfg.APIInfo != nil || mcfg.MongoInfo != nil {
return errors.New("machine configuration already has api/state info")
}
caCert, hasCACert := cfg.CACert()
if !hasCACert {
return errors.New("environment configuration has no ca-cert")
}
password := cfg.AdminSecret()
if password == "" {
return errors.New("environment configuration has no admin-secret")
}
passwordHash := utils.UserPasswordHash(password, utils.CompatSalt)
envUUID, uuidSet := cfg.UUID()
if !uuidSet {
return errors.New("config missing environment uuid")
}
mcfg.APIInfo = &api.Info{
Password: passwordHash,
CACert: caCert,
EnvironTag: names.NewEnvironTag(envUUID),
}
mcfg.MongoInfo = &mongo.MongoInfo{Password: passwordHash, Info: mongo.Info{CACert: caCert}}
// These really are directly relevant to running a state server.
// Initially, generate a state server certificate with no host IP
// addresses in the SAN field. Once the state server is up and the
// NIC addresses become known, the certificate can be regenerated.
cert, key, err := cfg.GenerateStateServerCertAndKey(nil)
if err != nil {
return errors.Annotate(err, "cannot generate state server certificate")
}
caPrivateKey, hasCAPrivateKey := cfg.CAPrivateKey()
if !hasCAPrivateKey {
return errors.New("environment configuration has no ca-private-key")
}
srvInfo := params.StateServingInfo{
StatePort: cfg.StatePort(),
APIPort: cfg.APIPort(),
Cert: string(cert),
PrivateKey: string(key),
CAPrivateKey: caPrivateKey,
}
mcfg.StateServingInfo = &srvInfo
if mcfg.Config, err = BootstrapConfig(cfg); err != nil {
return errors.Trace(err)
}
return nil
}
// isStateMachineConfig determines if given machine configuration
// is for State Server by iterating over machine's jobs.
// If JobManageEnviron is present, this is a state server.
func isStateMachineConfig(mcfg *cloudinit.MachineConfig) bool {
for _, aJob := range mcfg.Jobs {
if aJob == multiwatcher.JobManageEnviron {
return true
}
}
return false
}
func configureCloudinit(mcfg *cloudinit.MachineConfig, cloudcfg *coreCloudinit.Config) (cloudinit.UserdataConfig, error) {
// When bootstrapping, we only want to apt-get update/upgrade
// and setup the SSH keys. The rest we leave to cloudinit/sshinit.
udata, err := cloudinit.NewUserdataConfig(mcfg, cloudcfg)
if err != nil {
return nil, err
}
if mcfg.Bootstrap {
err = udata.ConfigureBasic()
if err != nil {
return nil, err
}
return udata, nil
}
err = udata.Configure()
if err != nil {
return nil, err
}
return udata, nil
}
// ComposeUserData fills out the provided cloudinit configuration structure
// so it is suitable for initialising a machine with the given configuration,
// and then renders it and returns it as a binary (gzipped) blob of user data.
//
// If the provided cloudcfg is nil, a new one will be created internally.
func ComposeUserData(mcfg *cloudinit.MachineConfig, cloudcfg *coreCloudinit.Config) ([]byte, error) {
if cloudcfg == nil {
cloudcfg = coreCloudinit.New()
}
udata, err := configureCloudinit(mcfg, cloudcfg)
if err != nil {
return nil, err
}
data, err := udata.Render()
logger.Tracef("Generated cloud init:\n%s", string(data))
if err != nil {
return nil, err
}
return utils.Gzip(data), nil
}