-
Notifications
You must be signed in to change notification settings - Fork 64
/
logs.go
104 lines (80 loc) · 2.18 KB
/
logs.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
// 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 logs
import (
"context"
"os"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
machineapi "kraftkit.sh/api/machine/v1alpha1"
"github.com/spf13/cobra"
"kraftkit.sh/cmdfactory"
"kraftkit.sh/compose"
kernellogs "kraftkit.sh/internal/cli/kraft/logs"
"kraftkit.sh/log"
mplatform "kraftkit.sh/machine/platform"
"kraftkit.sh/packmanager"
)
type LogsOptions struct {
Follow bool `long:"follow" usage:"Follow log output"`
Composefile string `noattribute:"true"`
}
func NewCmd() *cobra.Command {
cmd, err := cmdfactory.New(&LogsOptions{}, cobra.Command{
Short: "Print the logs of services in a project",
Use: "logs",
Annotations: map[string]string{
cmdfactory.AnnotationHelpGroup: "compose",
},
})
if err != nil {
panic(err)
}
return cmd
}
func (opts *LogsOptions) 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 *LogsOptions) 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
}
controller, err := mplatform.NewMachineV1alpha1ServiceIterator(ctx)
if err != nil {
return err
}
machinesToLog := []string{}
for _, service := range project.Services {
machine, _ := controller.Get(ctx, &machineapi.Machine{
ObjectMeta: metav1.ObjectMeta{
Name: service.Name,
},
})
if machine != nil {
machinesToLog = append(machinesToLog, machine.Name)
}
}
logOptions := kernellogs.LogOptions{
Follow: opts.Follow,
Platform: "auto",
}
return logOptions.Run(ctx, machinesToLog)
}