forked from juju/juju
/
provisioner.go
248 lines (209 loc) · 8 KB
/
provisioner.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
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package manual
import (
"bytes"
"fmt"
"io"
"strings"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/utils"
"github.com/juju/utils/shell"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/cloudconfig"
"github.com/juju/juju/cloudconfig/cloudinit"
"github.com/juju/juju/cloudconfig/instancecfg"
"github.com/juju/juju/cloudconfig/sshinit"
"github.com/juju/juju/instance"
"github.com/juju/juju/state/multiwatcher"
)
const manualInstancePrefix = "manual:"
var logger = loggo.GetLogger("juju.environs.manual")
// ProvisioningClientAPI defines the methods that are needed for the manual
// provisioning of machines. An interface is used here to decouple the API
// consumer from the actual API implementation type.
type ProvisioningClientAPI interface {
AddMachines([]params.AddMachineParams) ([]params.AddMachinesResult, error)
ForceDestroyMachines(machines ...string) error
ProvisioningScript(params.ProvisioningScriptParams) (script string, err error)
}
type ProvisionMachineArgs struct {
// Host is the SSH host: [user@]host
Host string
// DataDir is the root directory for juju data.
// If left blank, the default location "/var/lib/juju" will be used.
DataDir string
// Client provides the API needed to provision the machines.
Client ProvisioningClientAPI
// Stdin is required to respond to sudo prompts,
// and must be a terminal (except in tests)
Stdin io.Reader
// Stdout is required to present sudo prompts to the user.
Stdout io.Writer
// Stderr is required to present machine provisioning progress to the user.
Stderr io.Writer
// AuthorizedKeys contains the concatenated authorized-keys to add to the
// ubuntu user's ~/.ssh/authorized_keys.
AuthorizedKeys string
*params.UpdateBehavior
}
// ErrProvisioned is returned by ProvisionMachine if the target
// machine has an existing machine agent.
var ErrProvisioned = errors.New("machine is already provisioned")
// ProvisionMachine provisions a machine agent to an existing host, via
// an SSH connection to the specified host. The host may optionally be preceded
// with a login username, as in [user@]host.
//
// On successful completion, this function will return the id of the state.Machine
// that was entered into state.
func ProvisionMachine(args ProvisionMachineArgs) (machineId string, err error) {
defer func() {
if machineId != "" && err != nil {
logger.Errorf("provisioning failed, removing machine %v: %v", machineId, err)
if cleanupErr := args.Client.ForceDestroyMachines(machineId); cleanupErr != nil {
logger.Errorf("error cleaning up machine: %s", cleanupErr)
}
machineId = ""
}
}()
// Create the "ubuntu" user and initialise passwordless sudo. We populate
// the ubuntu user's authorized_keys file with the public keys in the current
// user's ~/.ssh directory. The authenticationworker will later update the
// ubuntu user's authorized_keys.
user, hostname := splitUserHost(args.Host)
if err := InitUbuntuUser(hostname, user, args.AuthorizedKeys, args.Stdin, args.Stdout); err != nil {
return "", err
}
machineParams, err := gatherMachineParams(hostname)
if err != nil {
return "", err
}
// Inform Juju that the machine exists.
machineId, err = recordMachineInState(args.Client, *machineParams)
if err != nil {
return "", err
}
provisioningScript, err := args.Client.ProvisioningScript(params.ProvisioningScriptParams{
MachineId: machineId,
Nonce: machineParams.Nonce,
DisablePackageCommands: !args.EnableOSRefreshUpdate && !args.EnableOSUpgrade,
})
if err != nil {
logger.Errorf("cannot obtain provisioning script")
return "", err
}
// Finally, provision the machine agent.
err = runProvisionScript(provisioningScript, hostname, args.Stderr)
if err != nil {
return machineId, err
}
logger.Infof("Provisioned machine %v", machineId)
return machineId, nil
}
func splitUserHost(host string) (string, string) {
if at := strings.Index(host, "@"); at != -1 {
return host[:at], host[at+1:]
}
return "", host
}
func recordMachineInState(client ProvisioningClientAPI, machineParams params.AddMachineParams) (machineId string, err error) {
results, err := client.AddMachines([]params.AddMachineParams{machineParams})
if err != nil {
return "", err
}
// Currently, only one machine is added, but in future there may be several added in one call.
machineInfo := results[0]
if machineInfo.Error != nil {
return "", machineInfo.Error
}
return machineInfo.Machine, nil
}
// gatherMachineParams collects all the information we know about the machine
// we are about to provision. It will SSH into that machine as the ubuntu user.
// The hostname supplied should not include a username.
// If we can, we will reverse lookup the hostname by its IP address, and use
// the DNS resolved name, rather than the name that was supplied
func gatherMachineParams(hostname string) (*params.AddMachineParams, error) {
// Generate a unique nonce for the machine.
uuid, err := utils.NewUUID()
if err != nil {
return nil, err
}
addr, err := HostAddress(hostname)
if err != nil {
return nil, errors.Annotatef(err, "failed to compute public address for %q", hostname)
}
provisioned, err := checkProvisioned(hostname)
if err != nil {
err = fmt.Errorf("error checking if provisioned: %v", err)
return nil, err
}
if provisioned {
return nil, ErrProvisioned
}
hc, series, err := DetectSeriesAndHardwareCharacteristics(hostname)
if err != nil {
err = fmt.Errorf("error detecting hardware characteristics: %v", err)
return nil, err
}
// There will never be a corresponding "instance" that any provider
// knows about. This is fine, and works well with the provisioner
// task. The provisioner task will happily remove any and all dead
// machines from state, but will ignore the associated instance ID
// if it isn't one that the environment provider knows about.
instanceId := instance.Id(manualInstancePrefix + hostname)
nonce := fmt.Sprintf("%s:%s", instanceId, uuid.String())
machineParams := ¶ms.AddMachineParams{
Series: series,
HardwareCharacteristics: hc,
InstanceId: instanceId,
Nonce: nonce,
Addrs: params.FromNetworkAddresses(addr),
Jobs: []multiwatcher.MachineJob{multiwatcher.JobHostUnits},
}
return machineParams, nil
}
var provisionMachineAgent = func(host string, icfg *instancecfg.InstanceConfig, progressWriter io.Writer) error {
script, err := ProvisioningScript(icfg)
if err != nil {
return err
}
return runProvisionScript(script, host, progressWriter)
}
// ProvisioningScript generates a bash script that can be
// executed on a remote host to carry out the cloud-init
// configuration.
func ProvisioningScript(icfg *instancecfg.InstanceConfig) (string, error) {
cloudcfg, err := cloudinit.New(icfg.Series)
if err != nil {
return "", errors.Annotate(err, "error generating cloud-config")
}
cloudcfg.SetSystemUpdate(icfg.EnableOSRefreshUpdate)
cloudcfg.SetSystemUpgrade(icfg.EnableOSUpgrade)
udata, err := cloudconfig.NewUserdataConfig(icfg, cloudcfg)
if err != nil {
return "", errors.Annotate(err, "error generating cloud-config")
}
if err := udata.ConfigureJuju(); err != nil {
return "", errors.Annotate(err, "error generating cloud-config")
}
configScript, err := cloudcfg.RenderScript()
if err != nil {
return "", errors.Annotate(err, "error converting cloud-config to script")
}
var buf bytes.Buffer
// Always remove the cloud-init-output.log file first, if it exists.
fmt.Fprintf(&buf, "rm -f %s\n", utils.ShQuote(icfg.CloudInitOutputLog))
// If something goes wrong, dump cloud-init-output.log to stderr.
buf.WriteString(shell.DumpFileOnErrorScript(icfg.CloudInitOutputLog))
buf.WriteString(configScript)
return buf.String(), nil
}
func runProvisionScript(script, host string, progressWriter io.Writer) error {
params := sshinit.ConfigureParams{
Host: "ubuntu@" + host,
ProgressWriter: progressWriter,
}
return sshinit.RunConfigureScript(script, params)
}