summaryrefslogtreecommitdiff
path: root/cmd/podman/machine/inspect.go
blob: 4600a2b6de38b19fef96e82eb007497b6da67c34 (plain)
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
//go:build amd64 || arm64
// +build amd64 arm64

package machine

import (
	"os"

	"github.com/containers/common/pkg/report"
	"github.com/containers/podman/v4/cmd/podman/common"
	"github.com/containers/podman/v4/cmd/podman/registry"
	"github.com/containers/podman/v4/cmd/podman/utils"
	"github.com/containers/podman/v4/pkg/machine"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

var (
	inspectCmd = &cobra.Command{
		Use:               "inspect [options] [MACHINE...]",
		Short:             "Inspect an existing machine",
		Long:              "Provide details on a managed virtual machine",
		RunE:              inspect,
		Example:           `podman machine inspect myvm`,
		ValidArgsFunction: autocompleteMachine,
	}
	inspectFlag = inspectFlagType{}
)

type inspectFlagType struct {
	format string
}

func init() {
	registry.Commands = append(registry.Commands, registry.CliCommand{
		Command: inspectCmd,
		Parent:  machineCmd,
	})

	flags := inspectCmd.Flags()
	formatFlagName := "format"
	flags.StringVar(&inspectFlag.format, formatFlagName, "", "Format volume output using JSON or a Go template")
	_ = inspectCmd.RegisterFlagCompletionFunc(formatFlagName, common.AutocompleteFormat(&machine.InspectInfo{}))
}

func inspect(cmd *cobra.Command, args []string) error {
	var (
		errs utils.OutputErrors
	)
	if len(args) < 1 {
		args = append(args, defaultMachineName)
	}
	vms := make([]machine.InspectInfo, 0, len(args))
	provider := GetSystemDefaultProvider()
	for _, vmName := range args {
		vm, err := provider.LoadVMByName(vmName)
		if err != nil {
			errs = append(errs, err)
			continue
		}
		ii, err := vm.Inspect()
		if err != nil {
			errs = append(errs, err)
			continue
		}
		vms = append(vms, *ii)
	}
	switch {
	case cmd.Flag("format").Changed:
		row := report.NormalizeFormat(inspectFlag.format)
		row = report.EnforceRange(row)

		tmpl, err := report.NewTemplate("Machine inspect").Parse(row)
		if err != nil {
			return err
		}

		w, err := report.NewWriterDefault(os.Stdout)
		if err != nil {
			return err
		}

		if err := tmpl.Execute(w, vms); err != nil {
			logrus.Error(err)
		}
		w.Flush()
	default:
		if err := printJSON(vms); err != nil {
			logrus.Error(err)
		}
	}
	return errs.PrintErrors()
}

func printJSON(data []machine.InspectInfo) error {
	enc := json.NewEncoder(os.Stdout)
	// by default, json marshallers will force utf=8 from
	// a string. this breaks healthchecks that use <,>, &&.
	enc.SetEscapeHTML(false)
	enc.SetIndent("", "     ")
	return enc.Encode(data)
}