Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/dev/preview/previewctl/cmd/stale.go
2500 views
1
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package cmd
6
7
import (
8
"context"
9
"fmt"
10
"time"
11
12
"github.com/sirupsen/logrus"
13
"github.com/spf13/cobra"
14
15
"github.com/gitpod-io/gitpod/previewctl/pkg/preview"
16
)
17
18
func newListStaleCmd(logger *logrus.Logger) *cobra.Command {
19
ctx := context.Background()
20
opts := &listWorkspaceOpts{
21
logger: logger,
22
}
23
24
cmd := &cobra.Command{
25
Use: "stale",
26
Short: "Get preview envs that are inactive (no branch with recent commits, and no db activity in the last 48h)",
27
RunE: func(cmd *cobra.Command, args []string) error {
28
statuses, err := opts.listWorskpaceStatus(ctx)
29
if err != nil {
30
return err
31
}
32
33
for _, ws := range statuses {
34
// this goes to stderr and is informational
35
opts.logger.WithFields(logrus.Fields{
36
"preview": ws.Name,
37
"active": ws.Active,
38
"reason": ws.Reason,
39
}).Info()
40
41
// this to stdout, so we can capture it easily
42
if !ws.Active {
43
fmt.Println(ws.Name)
44
}
45
}
46
47
return nil
48
},
49
}
50
51
cmd.PersistentFlags().StringVar(&opts.TFDir, "tf-dir", "dev/preview/infrastructure", "TF working directory")
52
cmd.Flags().DurationVarP(&opts.timeout, "timeout", "t", 10*time.Minute, "Duration to wait for a preview enviroment contexts' to get installed")
53
54
return cmd
55
}
56
57
func (o *listWorkspaceOpts) listWorskpaceStatus(ctx context.Context) ([]preview.Status, error) {
58
59
o.logger.Debug("Getting recent branches")
60
branches, err := preview.GetRecentBranches(time.Now().AddDate(0, 0, -2))
61
if err != nil {
62
return nil, err
63
}
64
65
o.logger.Debug("Getting terraform workspaces")
66
workspaces, err := o.getWorkspaces(ctx)
67
if err != nil {
68
return nil, err
69
}
70
71
statuses := make([]preview.Status, 0, len(workspaces))
72
for _, ws := range workspaces {
73
ws := ws
74
75
if _, ok := branches[ws]; ok {
76
statuses = append(statuses, preview.Status{
77
Name: ws,
78
Active: true,
79
Reason: "Branch has recent commits on it",
80
})
81
continue
82
}
83
84
p, err := preview.New(ws, o.logger)
85
if err != nil {
86
statuses = append(statuses, preview.Status{
87
Name: ws,
88
Active: false,
89
Reason: err.Error(),
90
})
91
continue
92
}
93
94
status, err := p.GetStatus(ctx)
95
if err != nil {
96
statuses = append(statuses, preview.Status{
97
Name: ws,
98
Active: false,
99
Reason: err.Error(),
100
})
101
continue
102
}
103
104
statuses = append(statuses, status)
105
}
106
107
return statuses, err
108
}
109
110