|
| 1 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package instance |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "errors" |
| 9 | + "time" |
| 10 | + |
| 11 | + networks "github.com/lima-vm/lima/pkg/networks/reconcile" |
| 12 | + "github.com/lima-vm/lima/pkg/store" |
| 13 | +) |
| 14 | + |
| 15 | +const launchHostAgentForeground = false |
| 16 | + |
| 17 | +func Restart(ctx context.Context, inst *store.Instance) error { |
| 18 | + if err := StopGracefully(inst); err != nil { |
| 19 | + return err |
| 20 | + } |
| 21 | + |
| 22 | + if err := waitForInstanceShutdown(ctx, inst); err != nil { |
| 23 | + return err |
| 24 | + } |
| 25 | + |
| 26 | + if err := networks.Reconcile(ctx, inst.Name); err != nil { |
| 27 | + return err |
| 28 | + } |
| 29 | + |
| 30 | + if err := Start(ctx, inst, "", launchHostAgentForeground); err != nil { |
| 31 | + return err |
| 32 | + } |
| 33 | + |
| 34 | + return nil |
| 35 | +} |
| 36 | + |
| 37 | +func RestartForcibly(ctx context.Context, inst *store.Instance) error { |
| 38 | + StopForcibly(inst) |
| 39 | + |
| 40 | + if err := networks.Reconcile(ctx, inst.Name); err != nil { |
| 41 | + return err |
| 42 | + } |
| 43 | + |
| 44 | + if err := Start(ctx, inst, "", launchHostAgentForeground); err != nil { |
| 45 | + return err |
| 46 | + } |
| 47 | + |
| 48 | + return nil |
| 49 | +} |
| 50 | + |
| 51 | +func waitForInstanceShutdown(ctx context.Context, inst *store.Instance) error { |
| 52 | + ctx2, cancel := context.WithTimeout(ctx, 3*time.Minute) |
| 53 | + defer cancel() |
| 54 | + |
| 55 | + ticker := time.NewTicker(500 * time.Millisecond) |
| 56 | + defer ticker.Stop() |
| 57 | + |
| 58 | + for { |
| 59 | + select { |
| 60 | + case <-ticker.C: |
| 61 | + updatedInst, err := store.Inspect(inst.Name) |
| 62 | + if err != nil { |
| 63 | + return errors.New("failed to inspect instance status: " + err.Error()) |
| 64 | + } |
| 65 | + |
| 66 | + if updatedInst.Status == store.StatusStopped { |
| 67 | + return nil |
| 68 | + } |
| 69 | + case <-ctx2.Done(): |
| 70 | + return errors.New("timed out waiting for instance to stop") |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments