-
Notifications
You must be signed in to change notification settings - Fork 62
/
ps.go
113 lines (94 loc) · 2.44 KB
/
ps.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
109
110
111
112
113
// 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 ps
import (
"context"
"os"
"github.com/MakeNowJust/heredoc"
"github.com/spf13/cobra"
"kraftkit.sh/cmdfactory"
"kraftkit.sh/compose"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
composeapi "kraftkit.sh/api/compose/v1"
pslist "kraftkit.sh/internal/cli/kraft/ps"
"kraftkit.sh/log"
"kraftkit.sh/packmanager"
)
type PsOptions struct {
composefile string
}
func NewCmd() *cobra.Command {
cmd, err := cmdfactory.New(&PsOptions{}, cobra.Command{
Short: "List running services of current project",
Use: "ps [FLAGS]",
Args: cobra.NoArgs,
Aliases: []string{},
Long: "List running services of current project.",
Example: heredoc.Doc(`
# List running services of current project
$ kraft compose ps
`),
Annotations: map[string]string{
cmdfactory.AnnotationHelpGroup: "compose",
},
})
if err != nil {
panic(err)
}
return cmd
}
func (opts *PsOptions) 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 *PsOptions) Run(ctx context.Context, args []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
}
pslistOptions := pslist.PsOptions{
Output: "table",
}
psTable, err := pslistOptions.PsTable(ctx)
if err != nil {
return err
}
controller, err := compose.NewComposeProjectV1(ctx)
if err != nil {
return err
}
embeddedProject, err := controller.Get(ctx, &composeapi.Compose{
ObjectMeta: metav1.ObjectMeta{
Name: project.Name,
},
})
if err != nil {
return err
}
filteredPsTable := []pslist.PsEntry{}
for _, psEntry := range psTable {
for _, machine := range embeddedProject.Status.Machines {
if psEntry.Name == machine.Name {
filteredPsTable = append(filteredPsTable, psEntry)
}
}
}
return pslistOptions.PrintPsTable(ctx, filteredPsTable)
}