-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathdeployment.go
More file actions
309 lines (267 loc) · 9.39 KB
/
Copy pathdeployment.go
File metadata and controls
309 lines (267 loc) · 9.39 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package cmd
import (
"bufio"
"bytes"
"context"
"embed"
"encoding/json"
"errors"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"text/template"
"github.com/charmbracelet/glamour"
"github.com/massdriver-cloud/mass/docs/helpdocs"
"github.com/massdriver-cloud/mass/internal/cli"
"github.com/massdriver-cloud/mass/internal/prettylogs"
"github.com/massdriver-cloud/massdriver-sdk-go/massdriver"
"github.com/massdriver-cloud/massdriver-sdk-go/massdriver/platform/deployments"
"github.com/massdriver-cloud/massdriver-sdk-go/massdriver/platform/types"
"github.com/spf13/cobra"
)
//go:embed templates/deployment.get.md.tmpl
var deploymentTemplates embed.FS
// NewCmdDeployment returns a cobra command for managing deployments.
func NewCmdDeployment() *cobra.Command {
deploymentCmd := &cobra.Command{
Use: "deployment",
Aliases: []string{"dep"},
Short: "Manage deployments",
Long: helpdocs.MustRender("deployment"),
}
deploymentGetCmd := &cobra.Command{
Use: "get <deployment-id>",
Short: "Get a deployment by ID",
Example: `mass deployment get 12345678-1234-1234-1234-123456789012`,
Long: helpdocs.MustRender("deployment/get"),
Args: cobra.ExactArgs(1),
RunE: runDeploymentGet,
}
deploymentGetCmd.Flags().StringP("output", "o", "text", "Output format (text or json)")
deploymentListCmd := &cobra.Command{
Use: "list <instance-id>",
Aliases: []string{"ls"},
Short: "List deployments for an instance (most recent first)",
Example: `mass deployment list ecomm-prod-db --limit 25`,
Long: helpdocs.MustRender("deployment/list"),
Args: cobra.ExactArgs(1),
RunE: runDeploymentList,
}
deploymentListCmd.Flags().IntP("limit", "n", 10, "Maximum number of deployments to return (max 100)")
deploymentListCmd.Flags().StringP("output", "o", "table", "Output format (table, json)")
deploymentListCmd.Flags().String("status", "", "Filter by status (pending, approved, running, completed, failed, aborted, rejected, proposed)")
deploymentListCmd.Flags().String("action", "", "Filter by action (provision, decommission, plan)")
deploymentListCmd.Flags().String("repo", "", "Filter by OCI repo name")
deploymentListCmd.Flags().String("bundle", "", "Filter by bundle version (name@version) or release channel (name@latest)")
deploymentLogsCmd := &cobra.Command{
Use: "logs <deployment-id>",
Short: "Stream the log output from a deployment",
Example: `mass deployment logs 12345678-1234-1234-1234-123456789012`,
Long: helpdocs.MustRender("deployment/logs"),
Args: cobra.ExactArgs(1),
RunE: runDeploymentLogs,
}
deploymentAbortCmd := &cobra.Command{
Use: "abort <deployment-id>",
Short: "Abort a pending, approved, or running deployment",
Example: `mass deployment abort 12345678-1234-1234-1234-123456789012 --force`,
Long: helpdocs.MustRender("deployment/abort"),
Args: cobra.ExactArgs(1),
RunE: runDeploymentAbort,
}
deploymentAbortCmd.Flags().BoolP("force", "f", false, "Skip confirmation prompt")
deploymentCmd.AddCommand(deploymentGetCmd)
deploymentCmd.AddCommand(deploymentListCmd)
deploymentCmd.AddCommand(deploymentLogsCmd)
deploymentCmd.AddCommand(deploymentAbortCmd)
return deploymentCmd
}
func runDeploymentGet(cmd *cobra.Command, args []string) error {
ctx := context.Background()
deploymentID := args[0]
outputFormat, err := cmd.Flags().GetString("output")
if err != nil {
return err
}
cmd.SilenceUsage = true
mdClient, err := massdriver.NewClient()
if err != nil {
return fmt.Errorf("error initializing massdriver client: %w", err)
}
deployment, err := mdClient.Deployments.Get(ctx, deploymentID)
if err != nil {
return err
}
switch outputFormat {
case "json":
jsonBytes, marshalErr := json.MarshalIndent(deployment, "", " ")
if marshalErr != nil {
return fmt.Errorf("failed to marshal deployment to JSON: %w", marshalErr)
}
fmt.Println(string(jsonBytes))
case "text":
return renderDeployment(deployment)
default:
return fmt.Errorf("unsupported output format: %s", outputFormat)
}
return nil
}
func runDeploymentList(cmd *cobra.Command, args []string) error {
ctx := context.Background()
instanceID := args[0]
limit, err := cmd.Flags().GetInt("limit")
if err != nil {
return err
}
status, _ := cmd.Flags().GetString("status")
action, _ := cmd.Flags().GetString("action")
repo, _ := cmd.Flags().GetString("repo")
bundle, _ := cmd.Flags().GetString("bundle")
output, _ := cmd.Flags().GetString("output")
cmd.SilenceUsage = true
mdClient, err := massdriver.NewClient()
if err != nil {
return fmt.Errorf("error initializing massdriver client: %w", err)
}
// SDK's Iter auto-paginates without a total cap; we want a total cap, so
// drive Iter and stop after `limit` items.
listInput := deployments.ListInput{
InstanceID: instanceID,
OciRepoName: repo,
BundleID: bundle,
SortBy: deployments.SortByCreatedAt,
SortOrder: deployments.SortDesc,
}
if status != "" {
listInput.Status = deployments.Status(strings.ToUpper(status))
}
if action != "" {
listInput.Action = deployments.Action(strings.ToUpper(action))
}
deps := make([]deployments.Deployment, 0, limit)
for d, iterErr := range mdClient.Deployments.Iter(ctx, listInput) {
if iterErr != nil {
return iterErr
}
if limit > 0 && len(deps) >= limit {
break
}
deps = append(deps, d)
}
switch output {
case "json":
jsonBytes, marshalErr := json.MarshalIndent(deps, "", " ")
if marshalErr != nil {
return fmt.Errorf("failed to marshal deployments to JSON: %w", marshalErr)
}
fmt.Println(string(jsonBytes))
return nil
case "table":
tbl := cli.NewTable("ID", "Action", "Status", "Version", "Created At", "By", "Message")
for _, d := range deps {
tbl.AddRow(d.ID, d.Action, d.Status, d.Version, d.CreatedAt, d.DeployedBy, cli.TruncateString(d.Message, 40))
}
tbl.Print()
return nil
default:
return fmt.Errorf("unsupported output format: %s", output)
}
}
func runDeploymentLogs(cmd *cobra.Command, args []string) error {
deploymentID := args[0]
cmd.SilenceUsage = true
ctx, cancel := signalContext(context.Background())
defer cancel()
mdClient, err := massdriver.NewClient()
if err != nil {
return fmt.Errorf("error initializing massdriver client: %w", err)
}
// TailLogs collapses backfill + terminal-check + live streaming into one call.
tailErr := mdClient.Deployments.TailLogs(ctx, deploymentID, os.Stdout)
if errors.Is(tailErr, deployments.ErrStreamingRequiresPAT) {
// Fall back to a one-shot static-log dump so the user still gets the
// available history. Streaming would require a personal access token.
fmt.Fprintln(os.Stderr, "warning: log streaming requires a personal access token (mds_*/md_*); showing static logs instead")
backfill, err := mdClient.Deployments.GetLogs(ctx, deploymentID)
if err != nil {
return fmt.Errorf("error getting deployment logs: %w", err)
}
fmt.Fprint(os.Stdout, backfill)
return nil
}
if tailErr != nil && !errors.Is(tailErr, context.Canceled) {
return tailErr
}
return nil
}
// signalContext returns a derived context that cancels on SIGINT/SIGTERM, so
// Ctrl-C cleanly tears down the WebSocket and exits.
func signalContext(parent context.Context) (context.Context, context.CancelFunc) {
return signal.NotifyContext(parent, syscall.SIGINT, syscall.SIGTERM)
}
func runDeploymentAbort(cmd *cobra.Command, args []string) error {
ctx := context.Background()
deploymentID := args[0]
force, err := cmd.Flags().GetBool("force")
if err != nil {
return err
}
cmd.SilenceUsage = true
if !force {
fmt.Printf("%s: This will abort deployment %s. A running deployment aborted mid-flight leaves any partial infrastructure changes in place, and does not halt execution of the deployment if it is already running.\n", prettylogs.Orange("WARNING"), deploymentID)
fmt.Printf("Type '%s' to confirm abort: ", deploymentID)
reader := bufio.NewReader(os.Stdin)
answer, _ := reader.ReadString('\n')
if strings.TrimSpace(answer) != deploymentID {
fmt.Println("Abort cancelled.")
return nil
}
}
mdClient, err := massdriver.NewClient()
if err != nil {
return fmt.Errorf("error initializing massdriver client: %w", err)
}
aborted, err := mdClient.Deployments.Abort(ctx, deploymentID)
if err != nil {
return err
}
fmt.Printf("✅ Deployment `%s` aborted (status: %s)\n", aborted.ID, aborted.Status)
return nil
}
//nolint:dupl // parallel template-render shape with renderInstance; consolidating would couple unrelated commands
func renderDeployment(deployment *types.Deployment) error {
tmplBytes, err := deploymentTemplates.ReadFile("templates/deployment.get.md.tmpl")
if err != nil {
return fmt.Errorf("failed to read template: %w", err)
}
tmpl, err := template.New("deployment").Funcs(cli.MarkdownTemplateFuncs).Parse(string(tmplBytes))
if err != nil {
return fmt.Errorf("failed to parse template: %w", err)
}
paramsJSON := "{}"
if deployment.Params != nil {
if b, marshalErr := json.MarshalIndent(deployment.Params, "", " "); marshalErr == nil {
paramsJSON = string(b)
}
}
data := struct {
*types.Deployment
ParamsJSON string
}{Deployment: deployment, ParamsJSON: paramsJSON}
var buf bytes.Buffer
if renderErr := tmpl.Execute(&buf, data); renderErr != nil {
return fmt.Errorf("failed to execute template: %w", renderErr)
}
r, err := glamour.NewTermRenderer(glamour.WithAutoStyle())
if err != nil {
return err
}
out, err := r.Render(buf.String())
if err != nil {
return err
}
fmt.Print(out)
return nil
}