kvm2.go 6.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// +build linux

/*
Copyright 2018 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package kvm2

import (
22
	"context"
23
	"fmt"
24
	"os"
25
	"os/exec"
26
	"os/user"
27
	"path/filepath"
T
tstromberg 已提交
28
	"strings"
29
	"time"
30 31

	"github.com/docker/machine/libmachine/drivers"
32

T
tstromberg 已提交
33
	"k8s.io/minikube/pkg/minikube/config"
34
	"k8s.io/minikube/pkg/minikube/download"
T
tstromberg 已提交
35
	"k8s.io/minikube/pkg/minikube/driver"
36
	"k8s.io/minikube/pkg/minikube/localpath"
37 38 39
	"k8s.io/minikube/pkg/minikube/registry"
)

40 41 42 43
const (
	docURL = "https://minikube.sigs.k8s.io/docs/reference/drivers/kvm2/"
)

44
func init() {
45
	if err := registry.Register(registry.DriverDef{
46
		Name:     driver.KVM2,
S
Sadlil 已提交
47
		Alias:    []string{driver.AliasKVM},
48 49
		Config:   configure,
		Status:   status,
50
		Default:  true,
51
		Priority: registry.Preferred,
52 53 54
	}); err != nil {
		panic(fmt.Sprintf("register failed: %v", err))
	}
55 56
}

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
// This is duplicate of kvm.Driver. Avoids importing the kvm2 driver, which requires cgo & libvirt.
type kvmDriver struct {
	*drivers.BaseDriver

	Memory         int
	DiskSize       int
	CPU            int
	Network        string
	PrivateNetwork string
	ISO            string
	Boot2DockerURL string
	DiskPath       string
	GPU            bool
	Hidden         bool
	ConnectionURI  string
72
	NUMANodeCount  int
73 74
}

S
Sharif Elgamal 已提交
75
func configure(cc config.ClusterConfig, n config.Node) (interface{}, error) {
D
Daehyeok Mun 已提交
76
	name := config.MachineName(cc, n)
77
	return kvmDriver{
78
		BaseDriver: &drivers.BaseDriver{
T
tstromberg 已提交
79
			MachineName: name,
80
			StorePath:   localpath.MiniPath(),
81 82
			SSHUser:     "docker",
		},
S
Sharif Elgamal 已提交
83 84 85
		Memory:         cc.Memory,
		CPU:            cc.CPUs,
		Network:        cc.KVMNetwork,
P
Predrag Rogic 已提交
86
		PrivateNetwork: privateNetwork(cc),
T
Thomas Stromberg 已提交
87
		Boot2DockerURL: download.LocalISOResource(cc.MinikubeISO),
S
Sharif Elgamal 已提交
88
		DiskSize:       cc.DiskSize,
T
tstromberg 已提交
89 90
		DiskPath:       filepath.Join(localpath.MiniPath(), "machines", name, fmt.Sprintf("%s.rawdisk", name)),
		ISO:            filepath.Join(localpath.MiniPath(), "machines", name, "boot2docker.iso"),
S
Sharif Elgamal 已提交
91 92 93
		GPU:            cc.KVMGPU,
		Hidden:         cc.KVMHidden,
		ConnectionURI:  cc.KVMQemuURI,
94
		NUMANodeCount:  cc.KVMNUMACount,
95
	}, nil
96
}
97

P
Predrag Rogic 已提交
98 99 100 101 102 103 104 105
// if network is not user-defined it defaults to "mk-<cluster_name>"
func privateNetwork(cc config.ClusterConfig) string {
	if cc.Network == "" {
		return fmt.Sprintf("mk-%s", cc.KubernetesConfig.ClusterName)
	}
	return cc.Network
}

106 107 108 109 110 111 112 113 114
// defaultURI returns the QEMU URI to connect to for health checks
func defaultURI() string {
	u := os.Getenv("LIBVIRT_DEFAULT_URI")
	if u != "" {
		return u
	}
	return "qemu:///system"
}

115
func status() registry.State {
116 117 118 119
	// Allow no more than 2 seconds for querying state
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

120
	path, err := exec.LookPath("virsh")
121 122 123 124
	if err != nil {
		return registry.State{Error: err, Fix: "Install libvirt", Doc: docURL}
	}

125 126
	member, err := isCurrentUserLibvirtGroupMember()
	if err != nil {
127 128 129
		return registry.State{
			Installed: true,
			Running:   true,
130 131 132 133 134
			// keep the error messsage in sync with reason.providerIssues(Kind.ID: "PR_KVM_USER_PERMISSION") regexp
			Error:  fmt.Errorf("libvirt group membership check failed:\n%v", err.Error()),
			Reason: "PR_KVM_USER_PERMISSION",
			Fix:    "Check that libvirtd is properly installed and that you are a member of the appropriate libvirt group (remember to relogin for group changes to take effect!)",
			Doc:    docURL,
135 136
		}
	}
137
	if !member {
138 139 140
		return registry.State{
			Installed: true,
			Running:   true,
141 142 143 144 145
			// keep the error messsage in sync with reason.providerIssues(Kind.ID: "PR_KVM_USER_PERMISSION") regexp
			Error:  fmt.Errorf("libvirt group membership check failed:\nuser is not a member of the appropriate libvirt group"),
			Reason: "PR_KVM_USER_PERMISSION",
			Fix:    "Check that libvirtd is properly installed and that you are a member of the appropriate libvirt group (remember to relogin for group changes to take effect!)",
			Doc:    docURL,
146 147 148
		}
	}

149
	// On Ubuntu 19.10 (libvirt 5.4), this fails if LIBVIRT_DEFAULT_URI is unset
150
	cmd := exec.CommandContext(ctx, path, "domcapabilities", "--virttype", "kvm")
151
	cmd.Env = append(os.Environ(), fmt.Sprintf("LIBVIRT_DEFAULT_URI=%s", defaultURI()))
T
tstromberg 已提交
152
	out, err := cmd.CombinedOutput()
153
	if err != nil {
154 155
		return registry.State{
			Installed: true,
156
			Running:   true,
157
			Error:     fmt.Errorf("%s failed:\n%s\n%v", strings.Join(cmd.Args, " "), strings.TrimSpace(string(out)), err),
158 159 160
			Fix:       "Follow your Linux distribution instructions for configuring KVM",
			Doc:       docURL,
		}
161 162
	}

163
	cmd = exec.CommandContext(ctx, "virsh", "list")
164
	cmd.Env = append(os.Environ(), fmt.Sprintf("LIBVIRT_DEFAULT_URI=%s", defaultURI()))
T
tstromberg 已提交
165
	out, err = cmd.CombinedOutput()
166
	if err != nil {
167 168
		return registry.State{
			Installed: true,
169
			Running:   true,
170
			Error:     fmt.Errorf("%s failed:\n%s", strings.Join(cmd.Args, " "), strings.TrimSpace(string(out))),
171
			Fix:       "Check that libvirtd is properly installed and that you are a member of the appropriate libvirt group (remember to relogin for group changes to take effect!)",
172 173
			Doc:       docURL,
		}
174
	}
175 176

	return registry.State{Installed: true, Healthy: true, Running: true}
177
}
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

// isCurrentUserLibvirtGroupMember returns if the current user is a member of "libvirt*" group.
func isCurrentUserLibvirtGroupMember() (bool, error) {
	usr, err := user.Current()
	if err != nil {
		return false, fmt.Errorf("error getting current user: %w", err)
	}
	gids, err := usr.GroupIds()
	if err != nil {
		return false, fmt.Errorf("error getting current user's GIDs: %w", err)
	}
	for _, gid := range gids {
		grp, err := user.LookupGroupId(gid)
		if err != nil {
			return false, fmt.Errorf("error getting current user's group with GID %q: %w", gid, err)
		}
		if strings.HasPrefix(grp.Name, "libvirt") {
			return true, nil
		}
	}
	return false, nil
}