This repository has been archived by the owner on Apr 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
driver.go
331 lines (283 loc) · 7.88 KB
/
driver.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
package driver
import (
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path/filepath"
"strconv"
"time"
"github.com/adnsio/docker-machine-driver-hyperkit/internal/dhcpdleases"
"github.com/adnsio/docker-machine-driver-hyperkit/internal/hyperkit"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnflag"
"github.com/docker/machine/libmachine/mcnutils"
"github.com/docker/machine/libmachine/ssh"
"github.com/docker/machine/libmachine/state"
"github.com/google/uuid"
)
const (
defaultHyperKitBinary = "hyperkit"
defaultISOInfoBinary = "isoinfo"
defaultDiskSize = 20000
defaultMemorySize = 1024
defaultCPUs = 1
)
// Driver is the Docker Machine driver for HyperKit
type Driver struct {
*drivers.BaseDriver
HyperKitBinary string
ISOInfoBinary string
Boot2DockerURL string
DiskSize int
MemorySize int
CPUs int
}
// New returns a new HyperKit driver
func New(machineName, storePath string) *Driver {
return &Driver{
HyperKitBinary: defaultHyperKitBinary,
DiskSize: defaultDiskSize,
MemorySize: defaultMemorySize,
CPUs: defaultCPUs,
BaseDriver: &drivers.BaseDriver{
MachineName: machineName,
StorePath: storePath,
},
}
}
// Create a host using the driver's config
func (d *Driver) Create() error {
// download and copy b2d ISO to StorePath
b2dUtils := mcnutils.NewB2dUtils(d.StorePath)
if err := b2dUtils.CopyIsoToMachineDir(d.Boot2DockerURL, d.MachineName); err != nil {
return err
}
// extract vmlinuz and initrd.img from b2d ISO
log.Info("Extracting Kernel and RAM disk from boot2docker ISO...")
if err := d.extractKernelAndRAMDiskFromB2DISO(); err != nil {
return err
}
sshKeyPath := d.GetSSHKeyPath()
// generate ssh keys
log.Info("Generating SSH keys...")
if err := ssh.GenerateSSHKey(sshKeyPath); err != nil {
return err
}
// create tar buffer with SSH keys for b2d
diskImageBuffer, err := mcnutils.MakeDiskImage(fmt.Sprintf("%s.pub", sshKeyPath))
if err != nil {
return err
}
// create disk file
diskFilePath := d.ResolveStorePath("disk.img")
log.Infof("Creating disk %s...", diskFilePath)
diskFile, err := os.Create(diskFilePath)
if err != nil {
return err
}
defer diskFile.Close()
if _, err := diskFile.Seek(0, io.SeekStart); err != nil {
return err
}
// write tar data to disk file
if _, err = diskFile.Write(diskImageBuffer.Bytes()); err != nil {
return err
}
// truncate disk file
if err := os.Truncate(diskFilePath, int64(d.DiskSize*1000000)); err != nil {
return err
}
// fix permissions of store path
storePath := d.ResolveStorePath("")
log.Infof("Fixing permissions of %s...", storePath)
if err := d.fixFilePermissions(storePath); err != nil {
return err
}
// fix permissions of all files
files, err := ioutil.ReadDir(storePath)
if err != nil {
return err
}
for _, file := range files {
filePath := filepath.Join(storePath, file.Name())
log.Infof("Fixing permissions of %s...", filePath)
if err := d.fixFilePermissions(filePath); err != nil {
return err
}
}
return d.Start()
}
// DriverName returns the name of the driver
func (d *Driver) DriverName() string {
return "hyperkit"
}
// GetCreateFlags returns the mcnflag.Flag slice representing the flags
// that can be set, their descriptions and defaults.
func (d *Driver) GetCreateFlags() []mcnflag.Flag {
return []mcnflag.Flag{
mcnflag.StringFlag{
Name: "hyperkit-binary",
Usage: "Path of the HyperKit binary.",
Value: defaultHyperKitBinary,
EnvVar: "HYPERKIT_BINARY",
},
mcnflag.StringFlag{
Name: "hyperkit-isoinfo-binary",
Usage: "Path of the isoinfo binary.",
Value: defaultISOInfoBinary,
EnvVar: "HYPERKIT_ISOINFO_BINARY",
},
mcnflag.StringFlag{
Name: "hyperkit-boot2docker-url",
Usage: "URL of the boot2docker ISO. Defaults to the latest version.",
EnvVar: "HYPERKIT_BOOT2DOCKER_URL",
},
mcnflag.IntFlag{
Name: "hyperkit-disk-size",
Usage: "Guest disk size in megabytes.",
Value: defaultDiskSize,
EnvVar: "HYPERKIT_DISK_SIZE",
},
mcnflag.IntFlag{
Name: "hyperkit-memory-size",
Usage: "Guest physical memory size in megabytes.",
Value: defaultMemorySize,
EnvVar: "HYPERKIT_MEMORY_SIZE",
},
mcnflag.IntFlag{
Name: "hyperkit-cpus",
Usage: "Number of guest virtual CPUs. The default is 1 and the maximum is 16.",
Value: defaultCPUs,
EnvVar: "HYPERKIT_CPUS",
},
}
}
// GetSSHHostname returns hostname for use with ssh
func (d *Driver) GetSSHHostname() (string, error) {
return d.GetIP()
}
// GetURL returns a Docker compatible host URL for connecting to this host
// e.g. tcp://1.2.3.4:2376
func (d *Driver) GetURL() (string, error) {
ip, err := d.GetIP()
if err != nil {
return "", err
}
if ip == "" {
return "", nil
}
return fmt.Sprintf("tcp://%s", net.JoinHostPort(ip, "2376")), nil
}
// GetState returns the state that the host is in (running, stopped, etc)
func (d *Driver) GetState() (state.State, error) {
_, err := d.findHyperKitProcess()
if err != nil {
if err == errHyperKitProcessNotFound {
return state.Stopped, nil
}
return state.Error, err
}
return state.Running, nil
}
// Kill stops a host forcefully
func (d *Driver) Kill() error {
return d.Stop()
}
// Remove a host
func (d *Driver) Remove() error {
return d.Stop()
}
// Restart a host. This may just call Stop(); Start() if the provider does not
// have any special restart behaviour.
func (d *Driver) Restart() error {
if err := d.Stop(); err != nil {
return err
}
return d.Start()
}
// SetConfigFromFlags configures the driver with the object that was returned
// by RegisterCreateFlags
func (d *Driver) SetConfigFromFlags(opts drivers.DriverOptions) error {
d.HyperKitBinary = opts.String("hyperkit-binary")
d.ISOInfoBinary = opts.String("hyperkit-isoinfo-binary")
d.Boot2DockerURL = opts.String("hyperkit-boot2docker-url")
d.DiskSize = opts.Int("hyperkit-disk-size")
d.MemorySize = opts.Int("hyperkit-memory-size")
d.CPUs = opts.Int("hyperkit-cpus")
d.SSHUser = "docker"
d.SetSwarmConfigFromFlags(opts)
return nil
}
// Start a host
func (d *Driver) Start() error {
machineUUID := uuid.NewSHA1(uuid.Nil, []byte(d.GetMachineName()))
macAddress := fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x",
machineUUID[0], machineUUID[1], machineUUID[2],
machineUUID[3], machineUUID[4], machineUUID[5])
log.Infof("UUID: %s", machineUUID)
log.Infof("MAC Address: %s", macAddress)
disk := d.ResolveStorePath("disk.img")
kernel := d.ResolveStorePath("vmlinuz")
ramDisk := d.ResolveStorePath("initrd.img")
hyperkit.HyperKitBinary = d.HyperKitBinary
hkConfig := &hyperkit.HyperKitConfiguration{
UUID: machineUUID.String(),
CPUs: d.CPUs,
MemorySize: d.MemorySize,
Disk: disk,
MACAddress: macAddress,
Kernel: kernel,
RamDisk: ramDisk,
Hostname: d.GetMachineName(),
}
hkCMD, err := hyperkit.Command(hkConfig)
if err != nil {
return err
}
log.Infof("CMD: %s", hkCMD.String())
if err := hkCMD.Start(); err != nil {
return err
}
log.Infof("PID: %d", hkCMD.Process.Pid)
pidFile, err := os.Create(d.ResolveStorePath("hyperkit.pid"))
if err != nil {
return err
}
defer pidFile.Close()
if _, err := pidFile.Write([]byte(strconv.Itoa(hkCMD.Process.Pid))); err != nil {
return err
}
for i := 0; i < 30; i++ {
log.Infof("Finding IP Address... (%d/30)", i+1)
d.IPAddress, err = dhcpdleases.FindIPAddress(dhcpdleases.DefaultDHCPDLeasesFile, macAddress)
if err == nil {
break
}
if err != dhcpdleases.ErrLeaseNotFound {
return err
}
time.Sleep(2 * time.Second)
}
if err != nil {
return err
}
log.Infof("IP Address: %s", d.IPAddress)
return nil
}
// Stop a host gracefully
func (d *Driver) Stop() error {
process, err := d.findHyperKitProcess()
if err != nil {
if err == errHyperKitProcessNotFound {
return nil
}
return err
}
if err := process.Kill(); err != nil {
return err
}
return nil
}