forked from skippbox/kmachine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
299 lines (244 loc) · 8.88 KB
/
utils.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
package provision
import (
"fmt"
"io/ioutil"
"net/url"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"crypto/rand"
"time"
"github.com/docker/machine/libmachine/auth"
"github.com/docker/machine/libmachine/cert"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnutils"
"github.com/docker/machine/libmachine/provision/serviceaction"
)
type DockerOptions struct {
EngineOptions string
EngineOptionsPath string
}
type k8sOptions struct {
k8sOptions string
k8sOptionsPath string
k8sKubeletCfg string
k8sKubeletPath string
k8sPolicyCfg string
}
func randToken() string {
b := make([]byte, 8)
rand.Read(b)
return fmt.Sprintf("%x", b)
}
func upgradeSystem(p Provisioner) error {
// We need to make sure the image has been upgraded as some later
// steps may fail
if output, err := p.SSHCommand(fmt.Sprintf("sudo DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::='--force-confdef' -o Dpkg::Options::='--force-confnew' dist-upgrade")); err != nil {
return fmt.Errorf("error upgrading aufs image: %s\n", output)
}
fmt.Printf("Rebooting system...\n");
if output, err := p.SSHCommand(fmt.Sprintf("sudo reboot")); err != nil {
return fmt.Errorf("error rebooting aufs image: %s\n", output)
}
drivers.WaitForSSH(p.GetDriver())
if output, err := p.SSHCommand(fmt.Sprintf("sudo apt-get update")); err != nil {
return fmt.Errorf("error refreshing packages: %s\n", output)
}
return nil
}
func installDockerGeneric(p Provisioner, baseURL string) error {
// install docker - until cloudinit we use ubuntu everywhere so we
// just install it using the docker repos
if output, err := p.SSHCommand(fmt.Sprintf("sudo apt-get -y install linux-image-extra-$(uname -r)")); err != nil {
return fmt.Errorf("error installing aufs image: %s\n", output)
}
if output, err := p.SSHCommand(fmt.Sprintf("if ! type docker; then curl -sSL %s | sh -; fi", baseURL)); err != nil {
return fmt.Errorf("error installing docker: %s\n", output)
}
return nil
}
func makeDockerOptionsDir(p Provisioner) error {
dockerDir := p.GetDockerOptionsDir()
if _, err := p.SSHCommand(fmt.Sprintf("sudo mkdir -p %s", dockerDir)); err != nil {
return err
}
return nil
}
func setRemoteAuthOptions(p Provisioner) auth.AuthOptions {
dockerDir := p.GetDockerOptionsDir()
authOptions := p.GetAuthOptions()
// due to windows clients, we cannot use filepath.Join as the paths
// will be mucked on the linux hosts
authOptions.CaCertRemotePath = path.Join(dockerDir, "ca.pem")
authOptions.ServerCertRemotePath = path.Join(dockerDir, "server.pem")
authOptions.ServerKeyRemotePath = path.Join(dockerDir, "server-key.pem")
return authOptions
}
func ConfigureAuth(p Provisioner) error {
var (
err error
)
driver := p.GetDriver()
machineName := driver.GetMachineName()
authOptions := p.GetAuthOptions()
org := mcnutils.GetUsername() + "." + machineName
bits := 2048
ip, err := driver.GetIP()
if err != nil {
return err
}
log.Info("Copying certs to the local machine directory...")
if err := mcnutils.CopyFile(authOptions.CaCertPath, filepath.Join(authOptions.StorePath, "ca.pem")); err != nil {
return fmt.Errorf("Copying ca.pem to machine dir failed: %s", err)
}
if err := mcnutils.CopyFile(authOptions.ClientCertPath, filepath.Join(authOptions.StorePath, "cert.pem")); err != nil {
return fmt.Errorf("Copying cert.pem to machine dir failed: %s", err)
}
if err := mcnutils.CopyFile(authOptions.ClientKeyPath, filepath.Join(authOptions.StorePath, "key.pem")); err != nil {
return fmt.Errorf("Copying key.pem to machine dir failed: %s", err)
}
log.Debugf("generating server cert: %s ca-key=%s private-key=%s org=%s",
authOptions.ServerCertPath,
authOptions.CaCertPath,
authOptions.CaPrivateKeyPath,
org,
)
// TODO: Switch to passing just authOptions to this func
// instead of all these individual fields
err = cert.GenerateCert(
[]string{ip, "localhost"},
authOptions.ServerCertPath,
authOptions.ServerKeyPath,
authOptions.CaCertPath,
authOptions.CaPrivateKeyPath,
org,
bits,
)
if err != nil {
return fmt.Errorf("error generating server cert: %s", err)
}
if err := p.Service("docker", serviceaction.Stop); err != nil {
return err
}
// upload certs and configure TLS auth
caCert, err := ioutil.ReadFile(authOptions.CaCertPath)
if err != nil {
return err
}
serverCert, err := ioutil.ReadFile(authOptions.ServerCertPath)
if err != nil {
return err
}
serverKey, err := ioutil.ReadFile(authOptions.ServerKeyPath)
if err != nil {
return err
}
log.Info("Copying certs to the remote machine...")
// printf will choke if we don't pass a format string because of the
// dashes, so that's the reason for the '%%s'
certTransferCmdFmt := "printf '%%s' '%s' | sudo tee %s"
// These ones are for Jessie and Mike <3 <3 <3
if _, err := p.SSHCommand(fmt.Sprintf(certTransferCmdFmt, string(caCert), authOptions.CaCertRemotePath)); err != nil {
return err
}
if _, err := p.SSHCommand(fmt.Sprintf(certTransferCmdFmt, string(serverCert), authOptions.ServerCertRemotePath)); err != nil {
return err
}
if _, err := p.SSHCommand(fmt.Sprintf(certTransferCmdFmt, string(serverKey), authOptions.ServerKeyRemotePath)); err != nil {
return err
}
dockerUrl, err := driver.GetURL()
if err != nil {
return err
}
u, err := url.Parse(dockerUrl)
if err != nil {
return err
}
dockerPort := 2376
parts := strings.Split(u.Host, ":")
if len(parts) == 2 {
dPort, err := strconv.Atoi(parts[1])
if err != nil {
return err
}
dockerPort = dPort
}
dkrcfg, err := p.GenerateDockerOptions(dockerPort)
if err != nil {
return err
}
log.Info("Setting Docker configuration on the remote daemon...")
if _, err = p.SSHCommand(fmt.Sprintf("printf %%s \"%s\" | sudo tee %s", dkrcfg.EngineOptions, dkrcfg.EngineOptionsPath)); err != nil {
return err
}
if err := p.Service("docker", serviceaction.Start); err != nil {
return err
}
return waitForDocker(p, dockerPort)
}
func installk8sGeneric(p Provisioner) error {
// install Kubernetes in a single node using Docker containers
//if output, err := p.SSHCommand("docker pull kubernetes/etcd"); err != nil {
// return fmt.Errorf("error installing k8s: %s\n", output)
//}
k8scfg, err := p.Generatek8sOptions()
if err != nil {
return err
}
if _, err = p.SSHCommand(fmt.Sprintf("printf '%s' | sudo tee %s", k8scfg.k8sOptions, k8scfg.k8sOptionsPath)); err != nil {
return err
}
if _, err := p.SSHCommand(fmt.Sprintf("printf '%%s' '%s'| sudo tee %s", k8scfg.k8sKubeletCfg, "/tmp/kube.conf")); err != nil {
return err
}
if _, err := p.SSHCommand(fmt.Sprintf("printf '%%s' '%s'| sudo tee %s", k8scfg.k8sPolicyCfg, "/tmp/policy.jsonl")); err != nil {
return err
}
if err := GenerateCertificates(p, p.GetKubernetesOptions(), p.GetAuthOptions()); err != nil {
return err
}
log.Debug("launching master")
if _, err := p.SSHCommand(fmt.Sprintf("sudo docker run -d --net=host --pid=host --privileged --restart=always --name head -v /sys:/sys:ro -v /var/run:/var/run:rw -v /:/rootfs:ro -v /dev:/dev -v /var/lib/docker/:/var/lib/docker:ro -v /var/lib/kubelet/:/var/lib/kubelet:rw -v /tmp/kube.conf:/etc/kubernetes/kubelet.kubeconfig -v /tmp/master.json:/etc/kubernetes/manifests/master.json -v /var/run/kubernetes/tokenfile.txt:/tmp/tokenfile.txt -v /tmp/policy.jsonl:/etc/kubernetes/policies/policy.jsonl gcr.io/google_containers/hyperkube:v1.1.2 /hyperkube kubelet --cluster-dns=10.0.0.10 --cluster-domain=cluster.local --containerized --allow-privileged=true --api_servers=http://localhost:8080 --v=2 --address=0.0.0.0 --enable_server --hostname_override=127.0.0.1 --config=/etc/kubernetes/manifests --kubeconfig=/etc/kubernetes/kubelet.kubeconfig")); err != nil {
return fmt.Errorf("error installing master")
}
return nil
}
func matchNetstatOut(reDaemonListening, netstatOut string) bool {
// TODO: I would really prefer this be a Scanner directly on
// the STDOUT of the executed command than to do all the string
// manipulation hokey-pokey.
//
// TODO: Unit test this matching.
for _, line := range strings.Split(netstatOut, "\n") {
match, err := regexp.MatchString(reDaemonListening, line)
if err != nil {
log.Warnf("Regex warning: %s", err)
}
if match && line != "" {
return true
}
}
return false
}
func checkDaemonUp(p Provisioner, dockerPort int) func() bool {
reDaemonListening := fmt.Sprintf(":%d.*LISTEN", dockerPort)
return func() bool {
// HACK: Check netstat's output to see if anyone's listening on the Docker API port.
netstatOut, err := p.SSHCommand("netstat -a")
if err != nil {
log.Warnf("Error running SSH command: %s", err)
return false
}
return matchNetstatOut(reDaemonListening, netstatOut)
}
}
func waitForDocker(p Provisioner, dockerPort int) error {
if err := mcnutils.WaitForSpecific(checkDaemonUp(p, dockerPort), 5, 3*time.Second); err != nil {
return NewErrDaemonAvailable(err)
}
return nil
}