From e69691c27747a5089658009418a3e427a93b3910 Mon Sep 17 00:00:00 2001
From: Shane Smith <shane.smith@shopify.com>
Date: Wed, 15 Jun 2022 15:42:50 -0400
Subject: [PATCH] Fix interrupting machine start leaves the machine unstartable

Interrupting a `podman machine start` (ex: with CTRL-C) would leave
`Starting: true` in the machine's config file. Due to #14469 any
subsequent starts would fail since Podman would think the machine is
still in the process of starting.

Fixed here by listening for the interrupt signal and setting `Starting:
false` in the event.

[NO NEW TESTS NEEDED]

Signed-off-by: Shane Smith <shane.smith@shopify.com>
---
 pkg/machine/qemu/machine.go | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)

diff --git a/pkg/machine/qemu/machine.go b/pkg/machine/qemu/machine.go
index f27e400435..288b2eeb04 100644
--- a/pkg/machine/qemu/machine.go
+++ b/pkg/machine/qemu/machine.go
@@ -16,9 +16,11 @@ import (
 	"net/url"
 	"os"
 	"os/exec"
+	"os/signal"
 	"path/filepath"
 	"strconv"
 	"strings"
+	"syscall"
 	"time"
 
 	"github.com/containers/common/pkg/config"
@@ -484,12 +486,26 @@ func (v *MachineVM) Start(name string, _ machine.StartOptions) error {
 	if err := v.writeConfig(); err != nil {
 		return fmt.Errorf("writing JSON file: %w", err)
 	}
-	defer func() {
+	doneStarting := func() {
 		v.Starting = false
 		if err := v.writeConfig(); err != nil {
 			logrus.Errorf("Writing JSON file: %v", err)
 		}
+	}
+	defer doneStarting()
+
+	c := make(chan os.Signal, 1)
+	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
+	go func() {
+		_, ok := <-c
+		if !ok {
+			return
+		}
+		doneStarting()
+		os.Exit(1)
 	}()
+	defer close(c)
+
 	if v.isIncompatible() {
 		logrus.Errorf("machine %q is incompatible with this release of podman and needs to be recreated, starting for recovery only", v.Name)
 	}