aboutsummaryrefslogtreecommitdiff
path: root/sessions.go
blob: b45aaee2d8fa51904df7e316e3339299d2d8d182 (plain) (blame)
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
package main

import (
	"fmt"
	"os"
	"text/tabwriter"

	"github.com/spf13/cobra"

	"git.onurgunduz.com/colabctl/internal/auth"
	"git.onurgunduz.com/colabctl/internal/colab"
	"git.onurgunduz.com/colabctl/internal/config"
)

var sessionsCmd = &cobra.Command{
	Use:     "sessions",
	Aliases: []string{"ps"},
	Short:   "List active Colab runtimes on your account",
	RunE: func(cmd *cobra.Command, _ []string) error {
		requireCredentials()

		httpClient, err := auth.Client(cmd.Context(), clientID, clientSecret)
		if err != nil {
			return err
		}
		client := colab.New(httpClient)

		runtimes, err := client.ListAssignments(cmd.Context())
		if err != nil {
			return err
		}

		if len(runtimes) == 0 {
			fmt.Println("No active runtimes.")
			return nil
		}

		w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
		fmt.Fprintln(w, "ENDPOINT\tACCELERATOR\tURL")
		fmt.Fprintln(w, "--------\t-----------\t---")
		for _, r := range runtimes {
			accel := r.Accelerator
			if accel == "" {
				accel = "CPU"
			}
			fmt.Fprintf(w, "%s\t%s\t%s\n", r.Endpoint, accel, r.URL)
		}
		return w.Flush()
	},
}

var stopCmd = &cobra.Command{
	Use:   "stop <endpoint>",
	Short: "Stop and release an active Colab runtime",
	Long: `Terminates the runtime identified by its endpoint ID.
Get the endpoint from:

  colabctl sessions`,
	Args: cobra.ExactArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		requireCredentials()

		endpoint := args[0]
		ctx := cmd.Context()

		httpClient, err := auth.Client(ctx, clientID, clientSecret)
		if err != nil {
			return err
		}
		client := colab.New(httpClient)

		fmt.Fprintf(os.Stderr, "Stopping runtime %s …\n", endpoint)
		if err := client.Unassign(ctx, endpoint); err != nil {
			return fmt.Errorf("stop runtime: %w", err)
		}
		_ = config.DeleteSession(endpoint)
		fmt.Println("Runtime stopped.")
		return nil
	},
}

func init() {
	rootCmd.AddCommand(sessionsCmd)
	rootCmd.AddCommand(stopCmd)
}