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
|
/*
Copyright 2021, Red Hat, Inc - 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 vfkit
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
"github.com/crc-org/crc/v2/pkg/crc/constants"
crcos "github.com/crc-org/crc/v2/pkg/os"
"github.com/crc-org/crc/v2/pkg/os/darwin"
"github.com/crc-org/machine/libmachine/drivers"
"github.com/crc-org/machine/libmachine/state"
"github.com/crc-org/vfkit/pkg/config"
"github.com/pkg/errors"
"github.com/shirou/gopsutil/v3/process"
log "github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
type Driver struct {
*drivers.VMDriver
VmlinuzPath string
Cmdline string
InitrdPath string
VfkitPath string
VirtioNet bool
VsockPath string
DaemonVsockPort uint
QemuGAVsockPort uint
}
func NewDriver(hostName, storePath string) *Driver {
// checks that vfdriver.Driver implements the libmachine.Driver interface
var _ drivers.Driver = &Driver{}
return &Driver{
VMDriver: &drivers.VMDriver{
BaseDriver: &drivers.BaseDriver{
MachineName: hostName,
StorePath: storePath,
},
CPU: DefaultCPUs,
Memory: DefaultMemory,
},
// needed when loading a VM which was created before
// DaemonVsockPort was introduced
DaemonVsockPort: constants.DaemonVsockPort,
}
}
// DriverName returns the name of the driver
func (d *Driver) DriverName() string {
return DriverName
}
// Get Version information
func (d *Driver) DriverVersion() string {
return DriverVersion
}
// GetIP returns an IP or hostname that this host is available at
// inherited from libmachine.BaseDriver
// func (d *Driver) GetIP() (string, error)
// GetMachineName returns the name of the machine
// inherited from libmachine.BaseDriver
// func (d *Driver) GetMachineName() string
// GetBundleName() Returns the name of the unpacked bundle which was used to create this machine
// inherited from libmachine.BaseDriver
// func (d *Driver) GetBundleName() (string, error)
// PreCreateCheck allows for pre-create operations to make sure a driver is ready for creation
func (d *Driver) PreCreateCheck() error {
return nil
}
func (d *Driver) getDiskPath() string {
return d.ResolveStorePath(fmt.Sprintf("%s.img", d.MachineName))
}
func (d *Driver) resize(newSize int64) error {
diskPath := d.getDiskPath()
fi, err := os.Stat(diskPath)
if err != nil {
return err
}
if newSize == fi.Size() {
log.Debugf("%s is already %d bytes", diskPath, newSize)
return nil
}
if newSize < fi.Size() {
return fmt.Errorf("current disk image capacity is bigger than the requested size (%d > %d)", fi.Size(), newSize)
}
return os.Truncate(diskPath, newSize)
}
// Create a host using the driver's config
func (d *Driver) Create() error {
if err := d.PreCreateCheck(); err != nil {
return err
}
switch d.ImageFormat {
case "raw":
if err := unix.Clonefile(d.ImageSourcePath, d.getDiskPath(), 0); err != nil {
// fall back to a regular sparse copy, the error may be caused by the filesystem not supporting unix.CloneFile
if err := crcos.CopyFileSparse(d.ImageSourcePath, d.getDiskPath()); err != nil {
return err
}
}
default:
return fmt.Errorf("%s is an unsupported disk image format", d.ImageFormat)
}
return d.resize(int64(d.DiskCapacity))
}
func startVfkit(vfkitPath string, args []string) (*os.Process, error) {
log.Debugf("Running %s %s", vfkitPath, strings.Join(args, " "))
cmd := exec.Command(vfkitPath, args...)
cmd.Stdout = log.StandardLogger().WriterLevel(log.DebugLevel)
cmd.Stderr = cmd.Stdout
cmd.Env = os.Environ()
if err := cmd.Start(); err != nil {
return nil, err
}
errCh := make(chan error, 1)
go func() {
errCh <- cmd.Wait()
}()
// catch vfkit early startup failures
select {
case err := <-errCh:
return nil, err
case <-time.After(time.Second):
break
}
return cmd.Process, nil
}
// Start a host
func (d *Driver) Start() error {
if err := d.recoverFromUncleanShutdown(); err != nil {
return err
}
bootLoader := config.NewLinuxBootloader(
d.VmlinuzPath,
"console=hvc0 "+d.Cmdline,
d.InitrdPath,
)
vm := config.NewVirtualMachine(
uint(d.CPU),
uint64(d.Memory),
bootLoader,
)
// console
logFile := d.ResolveStorePath("vfkit.log")
dev, err := config.VirtioSerialNew(logFile)
if err != nil {
return err
}
err = vm.AddDevice(dev)
if err != nil {
return err
}
// network
// 52:54:00 is the OUI used by QEMU
const mac = "52:54:00:70:2b:79"
if d.VirtioNet {
dev, err = config.VirtioNetNew(mac)
if err != nil {
return err
}
err = vm.AddDevice(dev)
if err != nil {
return err
}
}
// shared directories
if d.supportsVirtiofs() {
for _, sharedDir := range d.SharedDirs {
// TODO: add support for 'mount.ReadOnly'
// TODO: check format
dev, err := config.VirtioFsNew(sharedDir.Source, sharedDir.Tag)
if err != nil {
return err
}
err = vm.AddDevice(dev)
if err != nil {
return err
}
}
}
// entropy
dev, err = config.VirtioRngNew()
if err != nil {
return err
}
err = vm.AddDevice(dev)
if err != nil {
return err
}
// disk
diskPath := d.getDiskPath()
dev, err = config.VirtioBlkNew(diskPath)
if err != nil {
return err
}
err = vm.AddDevice(dev)
if err != nil {
return err
}
// virtio-vsock device
dev, err = config.VirtioVsockNew(d.DaemonVsockPort, d.VsockPath, true)
if err != nil {
return err
}
err = vm.AddDevice(dev)
if err != nil {
return err
}
// when loading a VM created by a crc version predating this commit,
// d.QemuGAVsockPort will be missing from ~/.crc/machines/crc/config.json
// In such a case, assume the VM will not support time sync
if d.QemuGAVsockPort != 0 {
timesync, err := config.TimeSyncNew(d.QemuGAVsockPort)
if err != nil {
return err
}
err = vm.AddDevice(timesync)
if err != nil {
return err
}
}
args, err := vm.ToCmdLine()
if err != nil {
return err
}
process, err := startVfkit(d.VfkitPath, args)
if err != nil {
return err
}
_ = os.WriteFile(d.getPidFilePath(), []byte(strconv.Itoa(process.Pid)), 0600)
if !d.VirtioNet {
return nil
}
getIP := func() error {
d.IPAddress, err = GetIPAddressByMACAddress(mac)
if err != nil {
return &RetriableError{Err: err}
}
return nil
}
if err := RetryAfter(60, getIP, 2*time.Second); err != nil {
return fmt.Errorf("IP address never found in dhcp leases file %v", err)
}
log.Debugf("IP: %s", d.IPAddress)
return nil
}
func (d *Driver) GetSharedDirs() ([]drivers.SharedDir, error) {
if !d.supportsVirtiofs() {
return nil, drivers.ErrNotSupported
}
// check if host supports file sharing, return drivers.ErrNotSupported if not
return d.SharedDirs, nil
}
// GetState returns the state that the host is in (running, stopped, etc)
func (d *Driver) GetState() (state.State, error) {
p, err := d.findVfkitProcess()
if err != nil {
return state.Error, err
}
if p == nil {
return state.Stopped, nil
}
return state.Running, nil
}
// Kill stops a host forcefully
func (d *Driver) Kill() error {
return d.sendSignal(syscall.SIGKILL)
}
// Remove a host
func (d *Driver) Remove() error {
s, err := d.GetState()
if err != nil || s == state.Error {
log.Debugf("Error checking machine status: %v, assuming it has been removed already", err)
}
if s == state.Running {
if err := d.Kill(); err != nil {
return err
}
}
return nil
}
// UpdateConfigRaw allows to change the state (memory, ...) of an already created machine
func (d *Driver) UpdateConfigRaw(rawConfig []byte) error {
var newDriver Driver
err := json.Unmarshal(rawConfig, &newDriver)
if err != nil {
return err
}
err = d.resize(int64(newDriver.DiskCapacity))
if err != nil {
log.Debugf("failed to resize disk image: %v", err)
return err
}
*d = newDriver
return nil
}
// Stop a host gracefully
func (d *Driver) Stop() error {
s, err := d.GetState()
if err != nil {
return err
}
if s != state.Stopped {
err := d.sendSignal(syscall.SIGTERM)
if err != nil {
return errors.Wrap(err, "vfkit sigterm failed")
}
// wait 120s for graceful shutdown
for i := 0; i < 60; i++ {
time.Sleep(2 * time.Second)
s, _ := d.GetState()
log.Debugf("VM state: %s", s)
if s == state.Stopped {
_ = os.Remove(d.getPidFilePath())
return nil
}
}
return errors.New("VM Failed to gracefully shutdown, try the kill command")
}
_ = os.Remove(d.getPidFilePath())
return nil
}
func (d *Driver) getPidFilePath() string {
const pidFileName = "vfkit.pid"
return d.ResolveStorePath(pidFileName)
}
/*
* Returns a ps.Process instance if it could find a vfkit process with the pid
* stored in $pidFileName
*
* Returns nil, nil if:
* - if the $pidFileName file does not exist,
* - if a process with the pid from this file cannot be found,
* - if a process was found, but its name is not 'vfkit'
*/
func (d *Driver) findVfkitProcess() (*process.Process, error) {
pidFile := d.getPidFilePath()
pid, err := readPidFromFile(pidFile)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
return nil, errors.Wrapf(err, "error reading pidfile %s", pidFile)
}
exists, err := process.PidExists(int32(pid))
if err != nil {
return nil, err
}
if !exists {
return nil, nil
}
p, err := process.NewProcess(int32(pid))
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("cannot find pid %d", pid))
}
if p == nil {
log.Debugf("vfkit pid %d missing from process table", pid)
// return PidNotExist error?
return nil, nil
}
name, err := p.Name()
if err != nil {
return nil, err
}
if !strings.HasPrefix(name, "vfkit") {
// return InvalidExecutable error?
log.Debugf("pid %d is stale, and is being used by %s", pid, name)
return nil, nil
}
return p, nil
}
func readPidFromFile(filename string) (int, error) {
bs, err := os.ReadFile(filename)
if err != nil {
return 0, err
}
content := strings.TrimSpace(string(bs))
pid, err := strconv.Atoi(content)
if err != nil {
return 0, errors.Wrapf(err, "parsing %s", filename)
}
return pid, nil
}
// recoverFromUncleanShutdown searches for an existing vfkit.pid file in
// the machine directory. If it can't find it, a clean shutdown is assumed.
// If it finds the pid file, it checks for a running vfkit process with that pid
// as the existence of a file might not indicate an unclean shutdown but an actual running
// vfkit server. This is an error situation - we shouldn't start minikube as there is likely
// an instance running already. If the PID in the pidfile does not belong to a running vfkit
// process, we can safely delete it, and there is a good chance the machine will recover when restarted.
func (d *Driver) recoverFromUncleanShutdown() error {
proc, err := d.findVfkitProcess()
if err == nil && proc != nil {
/* vfkit is running, pid file can't be stale */
return nil
}
pidFile := d.getPidFilePath()
/* There might be a stale pid file, try to remove it */
if err := os.Remove(pidFile); err != nil {
if !errors.Is(err, os.ErrNotExist) {
return errors.Wrap(err, fmt.Sprintf("removing pidFile %s", pidFile))
}
} else {
log.Debugf("Removed stale pid file %s...", pidFile)
}
return nil
}
func (d *Driver) sendSignal(s syscall.Signal) error {
proc, err := d.findVfkitProcess()
if err != nil {
return err
}
return proc.SendSignal(s)
}
func (d *Driver) supportsVirtiofs() bool {
supportsVirtioFS, err := darwin.AtLeast("12.0.0")
if err != nil {
log.Debugf("Not able to compare version: %v", err)
}
return supportsVirtioFS
}
|