File: machine.go

package info (click to toggle)
vagrant 2.3.7%2Bgit20230731.5fc64cde%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 17,616 kB
  • sloc: ruby: 111,820; sh: 462; makefile: 123; ansic: 34; lisp: 1
file content (513 lines) | stat: -rw-r--r-- 12,520 bytes parent folder | download | duplicates (2)
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
package core

import (
	"fmt"
	"os/user"
	"reflect"
	"sort"

	"github.com/mitchellh/mapstructure"
	"google.golang.org/protobuf/types/known/anypb"

	"github.com/hashicorp/go-hclog"
	"github.com/hashicorp/vagrant-plugin-sdk/component"
	"github.com/hashicorp/vagrant-plugin-sdk/core"
	"github.com/hashicorp/vagrant-plugin-sdk/helper/path"
	"github.com/hashicorp/vagrant-plugin-sdk/helper/types"
	"github.com/hashicorp/vagrant-plugin-sdk/internal-shared/cacher"
	"github.com/hashicorp/vagrant-plugin-sdk/proto/vagrant_plugin_sdk"
	"github.com/hashicorp/vagrant/internal/server/proto/vagrant_server"
)

type Machine struct {
	*Target
	box         *Box
	machine     *vagrant_server.Target_Machine
	logger      hclog.Logger
	cache       cacher.Cache
	vagrantfile *Vagrantfile
}

func (m *Machine) String() string {
	return fmt.Sprintf("core.Machine[basis: %s, project: %s, resource_id: %s, name: %s, address: %p]",
		m.project.basis.Name(), m.project.Name(), m.target.ResourceId, m.target.Name, m,
	)
}

// Close implements core.Machine
func (m *Machine) Close() (err error) {
	return
}

// ID implements core.Machine
func (m *Machine) ID() (id string, err error) {
	return m.machine.Id, nil
}

// SetID implements core.Machine
func (m *Machine) SetID(value string) (err error) {
	m.machine.Id = value

	// Also set uid
	user, err := user.Current()
	if err != nil {
		return err
	}
	m.machine.Uid = user.Uid

	// Persist changes
	if value == "" {
		m.target.Record = nil
		m.target.State = vagrant_server.Operation_NOT_CREATED
	}

	err = m.SaveMachine()

	return
}

func (m *Machine) Box() (b core.Box, err error) {
	if m.box == nil {
		boxes, _ := m.project.Boxes()
		boxName, err := m.vagrantfile.GetValue("vm", "box")
		if err != nil {
			m.logger.Error("failed to get machine box name from config",
				"error", err,
			)

			return nil, err
		}
		if boxName == nil {
			m.logger.Debug("vagrantfile has no box, so returning nil")
			return nil, nil
		}
		provider, err := m.ProviderName()
		if err != nil {
			return nil, err
		}
		b, err := boxes.Find(boxName.(string), "", provider)
		if err != nil {
			return nil, err
		}
		if b == nil {
			return &Box{
				basis: m.project.basis,
				box: &vagrant_server.Box{
					Name:     boxName.(string),
					Provider: provider,
				},
			}, nil
		}
		m.machine.Box = b.(*Box).ToProto()
		m.SaveMachine()
		m.box = b.(*Box)
	}

	return m.box, nil
}

// Guest implements core.Machine
func (m *Machine) Guest() (g core.Guest, err error) {
	comm, err := m.Communicate()
	if err != nil {
		return nil, err
	}
	isReady, err := comm.Ready(m)
	if err != nil {
		return nil, err
	}
	if !isReady {
		return nil, fmt.Errorf("unable to communicate with guest")
	}
	defer func() {
		if g != nil {
			err = seedPlugin(g, m)
			if err == nil {
				m.cache.Register("guest", g)
			}
		}
	}()

	// Note that if we get the guest value from the
	// local cache, we return it directly to prevent
	// the seeding and cache registration from happening
	// again.
	i := m.cache.Get("guest")
	if i != nil {
		return i.(core.Guest), nil
	}

	// Check if a guest is provided by the Vagrantfile. If it is, then try
	// to use that guest
	vg, err := m.vagrantfile.GetValue("vm", "guest")
	if err != nil {
		m.logger.Trace("failed to get guest value from vagrantfile",
			"error", err,
		)
	} else {
		guestName, ok := vg.(string)
		if ok {
			var guest *Component
			guest, err = m.project.basis.component(m.ctx, component.GuestType, guestName)
			if err != nil {
				return nil, err
			}
			g = guest.Value.(core.Guest)
			return
		} else {
			m.logger.Debug("guest name was not a valid string value",
				"guest", vg,
			)
		}

	}

	// Try to detect a guest
	guests, err := m.project.basis.typeComponents(m.ctx, component.GuestType)
	if err != nil {
		return
	}

	names := make([]string, 0, len(guests))
	pcount := map[string]int{}

	for name, g := range guests {
		names = append(names, name)
		pcount[name] = g.plugin.ParentCount()
	}

	sort.Slice(names, func(i, j int) bool {
		in := names[i]
		jn := names[j]
		// TODO check values exist before use
		return pcount[in] > pcount[jn]
	})

	for _, name := range names {
		guest := guests[name].Value.(core.Guest)
		detected, gerr := guest.Detect(m.toTarget())
		if gerr != nil {
			m.logger.Error("guest error on detection check",
				"plugin", name,
				"type", "Guest",
				"error", err)

			continue
		}
		if detected {
			m.logger.Info("guest detection complete",
				"name", name,
			)
			g = guest
			return
		}
	}

	return nil, fmt.Errorf("failed to detect guest plugin for current platform")
}

func (m *Machine) Inspect() (printable string, err error) {
	name, err := m.Name()
	provider, err := m.Provider()
	printable = "#<" + reflect.TypeOf(m).String() + ": " + name + " (" + reflect.TypeOf(provider).String() + ")>"
	return
}

// ConnectionInfo implements core.Machine
func (m *Machine) ConnectionInfo() (info *core.ConnectionInfo, err error) {
	// TODO: need Vagrantfile
	return
}

// MachineState implements core.Machine
func (m *Machine) MachineState() (state *core.MachineState, err error) {
	p, err := m.Provider()
	if err != nil {
		return nil, err
	}
	m.logger.Info("have machine provider plugin, getting state")
	s, err := p.State()
	m.logger.Info("provider state is returned",
		"state", s,
		"error", err,
	)
	return s, err
}

// SetMachineState implements core.Machine
func (m *Machine) SetMachineState(state *core.MachineState) (err error) {
	var st *vagrant_plugin_sdk.Args_Target_Machine_State
	if err := mapstructure.Decode(state, &st); err != nil {
		return err
	}
	m.machine.State = st

	switch st.Id {
	case "not_created":
		m.target.State = vagrant_server.Operation_NOT_CREATED
	case "running":
		m.target.State = vagrant_server.Operation_CREATED
	case "poweroff":
		m.target.State = vagrant_server.Operation_DESTROYED
	case "pending":
		m.target.State = vagrant_server.Operation_PENDING
	default:
		m.target.State = vagrant_server.Operation_UNKNOWN
	}

	return m.SaveMachine()
}

func (m *Machine) UID() (userId string, err error) {
	return m.machine.Uid, nil
}

func StringToPathFunc() mapstructure.DecodeHookFunc {
	return func(
		f reflect.Type,
		t reflect.Type,
		data interface{}) (interface{}, error) {
		if f.Kind() != reflect.String {
			return data, nil
		}
		if !t.Implements(reflect.TypeOf((*path.Path)(nil)).Elem()) {
			return data, nil
		}

		// Convert it
		return path.NewPath(data.(string)), nil
	}
}

func (m *Machine) defaultSyncedFolderType() (folderType string, err error) {
	logger := m.logger.Named("default-synced-folder-type")

	// Get all available synced folder plugins
	sfPlugins, err := m.project.basis.plugins.ListPlugins("synced_folder")
	if err != nil {
		return
	}

	// Load full plugins so we can read options
	for i, sfp := range sfPlugins {
		fullPlugin, err := m.project.basis.plugins.GetPlugin(sfp.Name, sfp.Type)
		if err != nil {
			logger.Error("error while loading synced folder plugin: name", sfp.Name, "err", err)
			return "", fmt.Errorf("error while loading synced folder plugin: name = %s, err = %s", sfp.Name, err)
		}
		sfPlugins[i] = fullPlugin
	}

	// Sort by plugin priority. Higher is first
	sort.SliceStable(sfPlugins, func(i, j int) bool {
		iPriority := sfPlugins[i].Options.(*component.SyncedFolderOptions).Priority
		jPriority := sfPlugins[j].Options.(*component.SyncedFolderOptions).Priority
		return iPriority > jPriority
	})

	logger.Debug("sorted synced folder plugins", "names", sfPlugins)

	allowedTypesRaw, err := m.vagrantfile.GetValue("vm", "allowed_synced_folder_types")
	if err != nil {
		m.logger.Warn("failed to fetch allowed synced folder types, ignoring",
			"error", err,
		)
		err = nil
	} else {
		allowedTypes, ok := allowedTypesRaw.([]interface{})
		if !ok {
			m.logger.Warn("unexpected type for allowed synced folder types",
				"type", hclog.Fmt("%T", allowedTypesRaw),
			)
		}
		// Remove unallowed types
		if len(allowedTypes) > 0 {
			allowed := make(map[string]struct{})
			for _, a := range allowedTypes {
				typ, err := optionToString(a)
				if err != nil {
					m.logger.Warn("failed to convert synced folder type to string",
						"type", hclog.Fmt("%T", a),
					)
				}
				allowed[typ] = struct{}{}
			}
			k := 0
			for _, sfp := range sfPlugins {
				if _, ok := allowed[sfp.Name]; ok {
					sfPlugins[k] = sfp
					k++
				} else {
					logger.Debug("removing disallowed plugin", "type", sfp.Name)
				}
			}
			sfPlugins = sfPlugins[:k]
		}
	}
	// Check for first usable plugin
	for _, sfp := range sfPlugins {
		syncedFolder := sfp.Plugin.(core.SyncedFolder)
		usable, err := syncedFolder.Usable(m)
		if err != nil {
			logger.Error("error on usable check", "plugin", sfp.Name, "error", err)
			continue
		}
		if usable {
			logger.Info("returning default", "name", sfp.Name)
			return sfp.Name, nil
		} else {
			logger.Debug("skipping unusable plugin", "name", sfp.Name)
		}
	}

	return "", fmt.Errorf("failed to detect guest plugin for current platform")
}

// SyncedFolders implements core.Machine
func (m *Machine) SyncedFolders() (folders []*core.MachineSyncedFolder, err error) {
	syncedFoldersRaw, err := m.vagrantfile.GetValue("vm", "__synced_folders")
	if err != nil {
		m.logger.Error("failed to load synced folders",
			"error", err,
		)

		return
	}
	tmpFolders, ok := syncedFoldersRaw.(map[interface{}]interface{})
	if !ok {
		m.logger.Error("synced folders configuration is unexpected type",
			"type", hclog.Fmt("%T", syncedFoldersRaw),
		)
		return nil, fmt.Errorf("invalid configuration type for synced folders")
	}

	syncedFolders := map[string]map[interface{}]interface{}{}

	for k, v := range tmpFolders {
		var key string
		var ok bool
		if key, ok = k.(string); !ok {
			if skey, ok := k.(types.Symbol); ok {
				key = string(skey)
			} else {
				m.logger.Error("invalid key type for synced folders",
					"key", k,
					"type", hclog.Fmt("%T", k),
				)

				return nil, fmt.Errorf("invalid configuration type for synced folder key")
			}
		}
		value, ok := v.(map[interface{}]interface{})
		if !ok {
			m.logger.Error("invalid value type for synced folders",
				"type", hclog.Fmt("%T", v),
			)
		}

		syncedFolders[key] = value
	}

	for _, options := range syncedFolders {
		var ftype string
		typeRaw, ok := getOptionValue("type", options)
		if ok {
			if ftype, err = optionToString(typeRaw); err != nil {
				m.logger.Debug("failed to convert folder type to string",
					"error", err,
				)

				return
			}
		}
		if ftype == "" {
			ftype, err = m.defaultSyncedFolderType()
			if err != nil {
				return nil, err
			}
		}

		lookup := "syncedfolder_" + ftype
		v := m.cache.Get(lookup)
		if v == nil {
			plg, err := m.project.basis.component(m.ctx, component.SyncedFolderType, ftype)
			if err != nil {
				return nil, err
			}
			v = plg.Value.(core.SyncedFolder)
			m.cache.Register(lookup, v)
		}

		if err = seedPlugin(v, m); err != nil {
			return nil, err
		}

		var guestPath, hostPath path.Path
		guestPathRaw, ok := getOptionValue("guestpath", options)
		if !ok {
			return nil, fmt.Errorf("synced folder options do not include guest path value")
		}
		hostPathRaw, ok := getOptionValue("hostpath", options)
		if !ok {
			return nil, fmt.Errorf("synced folder options do not include host path value")
		}
		if gps, err := optionToString(guestPathRaw); err == nil {
			guestPath = path.NewPath(gps)
		} else {
			return nil, err
		}
		if hps, err := optionToString(hostPathRaw); err == nil {
			hostPath = path.NewPath(hps)
		} else {
			return nil, err
		}

		opts := map[interface{}]interface{}{}
		for k, v := range options {
			key, err := optionToString(k)
			if err != nil {
				return nil, err
			}
			opts[key] = v
		}

		f := &core.Folder{
			Source:      hostPath,
			Destination: guestPath,
			Options:     opts,
		}

		folders = append(folders, &core.MachineSyncedFolder{
			Plugin: v.(core.SyncedFolder),
			Folder: f,
		})
	}
	return
}

func (m *Machine) AsTarget() (core.Target, error) {
	return m.Target, nil
}

func (m *Machine) SaveMachine() (err error) {
	m.logger.Debug("saving machine to db", "machine", m.machine.Id)
	// Update the target record and uuid to match the machine's new state
	m.target.Uuid = m.machine.Id
	m.target.Record, err = anypb.New(m.machine)
	if err != nil {
		m.logger.Warn("failed to convert machine data to any value",
			"error", err,
		)
		return
	}

	return m.Save()
}

func (m *Machine) toTarget() core.Target {
	return m
}

var _ core.Machine = (*Machine)(nil)
var _ core.Target = (*Machine)(nil)
var _ Scope = (*Machine)(nil)