-
Notifications
You must be signed in to change notification settings - Fork 62
/
stop.go
108 lines (88 loc) · 2.36 KB
/
stop.go
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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2024, Unikraft GmbH and The KraftKit Authors.
// Licensed under the BSD-3-Clause License (the "License").
// You may not use this file except in compliance with the License.
package stop
import (
"context"
"os"
"github.com/MakeNowJust/heredoc"
"github.com/spf13/cobra"
"kraftkit.sh/cmdfactory"
"kraftkit.sh/compose"
"kraftkit.sh/log"
"kraftkit.sh/packmanager"
machineapi "kraftkit.sh/api/machine/v1alpha1"
kernelstop "kraftkit.sh/internal/cli/kraft/stop"
mplatform "kraftkit.sh/machine/platform"
)
type StopOptions struct {
composefile string
}
func NewCmd() *cobra.Command {
cmd, err := cmdfactory.New(&StopOptions{}, cobra.Command{
Short: "Stop a compose project",
Use: "stop [FLAGS]",
Args: cobra.NoArgs,
Aliases: []string{},
Example: heredoc.Doc(`
# Stop a compose project
$ kraft compose stop
`),
Annotations: map[string]string{
cmdfactory.AnnotationHelpGroup: "compose",
},
})
if err != nil {
panic(err)
}
return cmd
}
func (opts *StopOptions) Pre(cmd *cobra.Command, _ []string) error {
ctx, err := packmanager.WithDefaultUmbrellaManagerInContext(cmd.Context())
if err != nil {
return err
}
cmd.SetContext(ctx)
if cmd.Flag("file").Changed {
opts.composefile = cmd.Flag("file").Value.String()
}
log.G(cmd.Context()).WithField("composefile", opts.composefile).Debug("using")
return nil
}
func (opts *StopOptions) Run(ctx context.Context, _ []string) error {
workdir, err := os.Getwd()
if err != nil {
return err
}
project, err := compose.NewProjectFromComposeFile(ctx, workdir, opts.composefile)
if err != nil {
return err
}
if err := project.Validate(ctx); err != nil {
return err
}
machineController, err := mplatform.NewMachineV1alpha1ServiceIterator(ctx)
if err != nil {
return err
}
machines, err := machineController.List(ctx, &machineapi.MachineList{})
if err != nil {
return err
}
machinesToStop := []string{}
for _, service := range project.Services {
for _, machine := range machines.Items {
if service.Name == machine.Name && machine.Status.State == machineapi.MachineStateRunning {
machinesToStop = append(machinesToStop, machine.Name)
}
}
}
if len(machinesToStop) == 0 {
return nil
}
kernelStopOptions := kernelstop.StopOptions{
Platform: "auto",
}
return kernelStopOptions.Run(ctx, machinesToStop)
}