| 1 | |
| 2 | |
| 3 | |
| 4 | package hcs |
| 5 | |
| 6 | import ( |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "net" |
| 14 | "os" |
| 15 | "os/exec" |
| 16 | "path/filepath" |
| 17 | "strings" |
| 18 | "syscall" |
| 19 | |
| 20 | "github.com/Microsoft/hcsshim/hcn" |
| 21 | "github.com/lima-vm/go-qcow2reader/image/qcow2" |
| 22 | "github.com/lima-vm/go-qcow2reader/image/vhdx" |
| 23 | "github.com/sirupsen/logrus" |
| 24 | |
| 25 | "github.com/lima-vm/lima/v2/pkg/imgutil/nativeimgutil" |
| 26 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 27 | "github.com/lima-vm/lima/v2/pkg/limayaml" |
| 28 | ) |
| 29 | |
| 30 | const ( |
| 31 | |
| 32 | hcsTimeoutInfinite uint32 = 0xFFFFFFFF |
| 33 | |
| 34 | |
| 35 | netFlagEnableDNS hcn.NetworkFlags = 1 |
| 36 | netFlagEnableDHCP hcn.NetworkFlags = 2 |
| 37 | netFlagIsolateSwitch hcn.NetworkFlags = 32 |
| 38 | |
| 39 | networkAddressPrefix = "192.168.10.0/24" |
| 40 | networkGateway = "192.168.10.1" |
| 41 | ) |
| 42 | |
| 43 | type computeSystemProperties struct { |
| 44 | State string `json:"State"` |
| 45 | } |
| 46 | |
| 47 | var errNotFound = errors.New("not found") |
| 48 | |
| 49 | |
| 50 | func getComputeSystemState(ctx context.Context, id string) (string, error) { |
| 51 | system, err := hcsOpenComputeSystem(ctx, id, syscall.GENERIC_ALL) |
| 52 | if err != nil { |
| 53 | return "", errNotFound |
| 54 | } |
| 55 | defer hcsCloseComputeSystem(system) |
| 56 | |
| 57 | op, err := hcsCreateOperation() |
| 58 | if err != nil { |
| 59 | return "", fmt.Errorf("failed to create an HCS operation: %w", err) |
| 60 | } |
| 61 | defer hcsCloseOperation(op) |
| 62 | |
| 63 | if err := hcsGetComputeSystemProperties(ctx, system, op, "{}"); err != nil { |
| 64 | return "", fmt.Errorf("failed to get compute system properties: %w", err) |
| 65 | } |
| 66 | |
| 67 | result, err := hcsWait(op, "hcsGetComputeSystemProperties", nil) |
| 68 | if err != nil { |
| 69 | return "", fmt.Errorf("failed to get compute system properties: %w (result=%s)", err, result) |
| 70 | } |
| 71 | |
| 72 | var properties computeSystemProperties |
| 73 | if err := json.Unmarshal([]byte(result), &properties); err != nil { |
| 74 | return "", fmt.Errorf("failed to decode compute system properties: %w", err) |
| 75 | } |
| 76 | |
| 77 | return properties.State, nil |
| 78 | } |
| 79 | |
| 80 | |
| 81 | func buildVMConfig( |
| 82 | diskPath, isoPath, endpointID, macAddress, serialPipe string, |
| 83 | cpus int, memoryMiB int64, |
| 84 | ) (string, error) { |
| 85 | config := map[string]any{ |
| 86 | "SchemaVersion": map[string]any{ |
| 87 | "Major": 2, |
| 88 | "Minor": 1, |
| 89 | }, |
| 90 | "Owner": "Lima", |
| 91 | "ShouldTerminateOnLastHandleClosed": true, |
| 92 | "VirtualMachine": map[string]any{ |
| 93 | "Chipset": map[string]any{ |
| 94 | "Uefi": map[string]any{ |
| 95 | "Console": "ComPort1", |
| 96 | "BootThis": map[string]any{ |
| 97 | "DevicePath": "Primary disk", |
| 98 | "DiskNumber": 0, |
| 99 | "DeviceType": "ScsiDrive", |
| 100 | }, |
| 101 | }, |
| 102 | }, |
| 103 | "ComputeTopology": map[string]any{ |
| 104 | "Memory": map[string]any{ |
| 105 | "Backing": "Virtual", |
| 106 | "SizeInMB": memoryMiB, |
| 107 | }, |
| 108 | "Processor": map[string]any{ |
| 109 | "Count": cpus, |
| 110 | }, |
| 111 | }, |
| 112 | "Devices": map[string]any{ |
| 113 | "Scsi": map[string]any{ |
| 114 | "Primary disk": map[string]any{ |
| 115 | "Attachments": map[string]any{ |
| 116 | "0": map[string]any{ |
| 117 | "Type": "VirtualDisk", |
| 118 | "Path": diskPath, |
| 119 | }, |
| 120 | }, |
| 121 | }, |
| 122 | "cidata": map[string]any{ |
| 123 | "Attachments": map[string]any{ |
| 124 | "0": map[string]any{ |
| 125 | "Type": "Iso", |
| 126 | "Path": isoPath, |
| 127 | }, |
| 128 | }, |
| 129 | }, |
| 130 | }, |
| 131 | "ComPorts": map[string]any{ |
| 132 | "0": map[string]any{ |
| 133 | "NamedPipe": serialPipe, |
| 134 | }, |
| 135 | }, |
| 136 | "NetworkAdapters": map[string]any{ |
| 137 | endpointID: map[string]any{ |
| 138 | "EndpointId": endpointID, |
| 139 | "MacAddress": macAddress, |
| 140 | }, |
| 141 | }, |
| 142 | }, |
| 143 | }, |
| 144 | } |
| 145 | |
| 146 | configBytes, err := json.Marshal(config) |
| 147 | if err != nil { |
| 148 | return "", err |
| 149 | } |
| 150 | |
| 151 | return string(configBytes), nil |
| 152 | } |
| 153 | |
| 154 | func ensureNetwork(name string) (*hcn.HostComputeNetwork, error) { |
| 155 | network, err := hcn.GetNetworkByName(name) |
| 156 | if err == nil { |
| 157 | return network, nil |
| 158 | } |
| 159 | |
| 160 | if !hcn.IsNotFoundError(err) { |
| 161 | return nil, fmt.Errorf("failed to look up the HCN network %#q: %w", name, err) |
| 162 | } |
| 163 | |
| 164 | network = &hcn.HostComputeNetwork{ |
| 165 | Name: name, |
| 166 | SchemaVersion: hcn.V2SchemaVersion(), |
| 167 | Type: hcn.ICS, |
| 168 | Flags: netFlagEnableDNS | netFlagEnableDHCP | hcn.EnableNonPersistent | netFlagIsolateSwitch, |
| 169 | Ipams: []hcn.Ipam{{ |
| 170 | Type: "Static", |
| 171 | Subnets: []hcn.Subnet{{ |
| 172 | IpAddressPrefix: networkAddressPrefix, |
| 173 | Routes: []hcn.Route{{ |
| 174 | NextHop: networkGateway, |
| 175 | DestinationPrefix: "0.0.0.0/0", |
| 176 | }}, |
| 177 | }}, |
| 178 | }}, |
| 179 | } |
| 180 | |
| 181 | return network.Create() |
| 182 | } |
| 183 | |
| 184 | func ensureEndpoint(network *hcn.HostComputeNetwork, name, instDir string) (*hcn.HostComputeEndpoint, error) { |
| 185 | endpoint, err := hcn.GetEndpointByName(name) |
| 186 | if err == nil { |
| 187 | if endpoint.HostComputeNetwork != network.Id { |
| 188 | return nil, fmt.Errorf("endpoint %#q already exists on a different network", name) |
| 189 | } |
| 190 | return endpoint, nil |
| 191 | } |
| 192 | if !hcn.IsNotFoundError(err) { |
| 193 | return nil, err |
| 194 | } |
| 195 | |
| 196 | endpoint = &hcn.HostComputeEndpoint{ |
| 197 | Name: name, |
| 198 | SchemaVersion: hcn.V2SchemaVersion(), |
| 199 | HostComputeNetwork: network.Id, |
| 200 | MacAddress: hnsMACAddress(instDir), |
| 201 | } |
| 202 | |
| 203 | return endpoint.Create() |
| 204 | } |
| 205 | |
| 206 | func networkName(instName string) string { |
| 207 | return "lima-" + instName + "-net" |
| 208 | } |
| 209 | |
| 210 | func endpointName(instName string) string { |
| 211 | return "lima-" + instName + "-ep" |
| 212 | } |
| 213 | |
| 214 | |
| 215 | func hnsMACAddress(instDir string) string { |
| 216 | return strings.ToUpper(strings.ReplaceAll(limayaml.MACAddress(instDir), ":", "-")) |
| 217 | } |
| 218 | |
| 219 | |
| 220 | func createComputeSystem(_ context.Context, id, config string) (hcsSystem, error) { |
| 221 | system, err := hcsCreateComputeSystem(id, config) |
| 222 | if err != nil { |
| 223 | return 0, fmt.Errorf("create compute system error: %w", err) |
| 224 | } |
| 225 | |
| 226 | return system, nil |
| 227 | } |
| 228 | |
| 229 | func startComputeSystem(_ context.Context, system hcsSystem) error { |
| 230 | return hcsStartComputeSystem(system) |
| 231 | } |
| 232 | |
| 233 | func terminateComputeSystem(_ context.Context, system hcsSystem) error { |
| 234 | return hcsTerminateComputeSystem(system) |
| 235 | } |
| 236 | |
| 237 | |
| 238 | |
| 239 | func serveSerial(ln net.Listener, logPath string) { |
| 240 | f, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) |
| 241 | if err != nil { |
| 242 | logrus.WithError(err).Errorf("failed to open the serial log %#q", logPath) |
| 243 | return |
| 244 | } |
| 245 | defer f.Close() |
| 246 | |
| 247 | for { |
| 248 | conn, err := ln.Accept() |
| 249 | if err != nil { |
| 250 | if errors.Is(err, net.ErrClosed) { |
| 251 | return |
| 252 | } |
| 253 | logrus.WithError(err).Warn("failed to accept a serial connection") |
| 254 | return |
| 255 | } |
| 256 | logrus.Debugf("serial: the guest connected to %s", ln.Addr()) |
| 257 | if _, err := io.Copy(f, conn); err != nil { |
| 258 | logrus.WithError(err).Debug("serial: copy finished with an error") |
| 259 | } |
| 260 | conn.Close() |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | |
| 265 | func mayConvertQcow2ToVHDX(ctx context.Context, instDir string) error { |
| 266 | disk := filepath.Join(instDir, filenames.Disk) |
| 267 | _, err := os.Stat(disk) |
| 268 | if err == nil { |
| 269 | return nil |
| 270 | } |
| 271 | if !os.IsNotExist(err) { |
| 272 | return err |
| 273 | } |
| 274 | |
| 275 | imagePath := filepath.Join(instDir, filenames.Image) |
| 276 | format, err := nativeimgutil.DetectFormat(imagePath) |
| 277 | if err != nil { |
| 278 | return err |
| 279 | } |
| 280 | |
| 281 | switch format { |
| 282 | case string(vhdx.Type): |
| 283 | logrus.Debug("disk is already .vhdx") |
| 284 | if err = os.Rename(imagePath, disk); err != nil { |
| 285 | return fmt.Errorf("failed to rename %#q to %#q: %w", imagePath, disk, err) |
| 286 | } |
| 287 | if err := os.Chmod(disk, 0o644); err != nil { |
| 288 | return fmt.Errorf("failed to chmod %#q: %w", disk, err) |
| 289 | } |
| 290 | return nil |
| 291 | case qcow2.Type, "raw": |
| 292 | if err := execQemuImgConvert(ctx, imagePath, disk); err != nil { |
| 293 | return fmt.Errorf("failed to convert to vhdx: %w", err) |
| 294 | } |
| 295 | if err := execFsutil(ctx, disk); err != nil { |
| 296 | return fmt.Errorf("failed to set disk flag: %w", err) |
| 297 | } |
| 298 | return nil |
| 299 | default: |
| 300 | return fmt.Errorf("disk type %s is not supported", format) |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | func execQemuImgConvert(ctx context.Context, source, dist string) error { |
| 305 | var stdout, stderr bytes.Buffer |
| 306 | cmd := exec.CommandContext(ctx, "qemu-img", "convert", "-O", "vhdx", source, dist) |
| 307 | cmd.Stdout = &stdout |
| 308 | cmd.Stderr = &stderr |
| 309 | if err := cmd.Run(); err != nil { |
| 310 | return fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q: %w", |
| 311 | cmd.Args, stdout.String(), stderr.String(), err) |
| 312 | } |
| 313 | return nil |
| 314 | } |
| 315 | |
| 316 | func execFsutil(ctx context.Context, disk string) error { |
| 317 | var stdout, stderr bytes.Buffer |
| 318 | cmd := exec.CommandContext(ctx, "fsutil", "sparse", "setflag", disk, "0") |
| 319 | cmd.Stdout = &stdout |
| 320 | cmd.Stderr = &stderr |
| 321 | if err := cmd.Run(); err != nil { |
| 322 | return fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q: %w", cmd.Args, stdout.String(), stderr.String(), err) |
| 323 | } |
| 324 | return nil |
| 325 | } |