/
main.go
236 lines (214 loc) · 7 KB
/
main.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
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
package main
import (
"context"
"errors"
"fmt"
stdlog "log"
"os"
"strings"
"github.com/alecthomas/kingpin"
kitlog "github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp" // this is required to auth against GCP
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog"
workloadsv1alpha1 "github.com/gocardless/theatre/v2/apis/workloads/v1alpha1"
"github.com/gocardless/theatre/v2/cmd"
"github.com/gocardless/theatre/v2/pkg/signals"
"github.com/gocardless/theatre/v2/pkg/workloads/console/runner"
)
var (
cli = kingpin.New("consoles", "Manages theatre consoles").Version(cmd.VersionStanza())
cliContext = cli.Flag("context", "Kubernetes context to target. If not provided defaults to current context").
Short('c').
Envar("KUBERNETES_CONTEXT").
String()
cliNamespace = cli.Flag("namespace", "Kubernetes namespace to target. If not provided defaults to target allnamespaces").
Short('n').
Envar("KUBERNETES_NAMESPACE").
String()
create = cli.Command("create", "Creates a new console given a template")
createSelector = create.Flag("selector", "Selector to match a console template").
Short('s').
Required().
String()
createTimeout = create.Flag("timeout", "Timeout for the new console").
Duration()
createReason = create.Flag("reason", "Reason for creating console").
String()
createNoninteractive = create.Flag("noninteractive", "Do not enable TTY and STDIN on console container").
Bool()
createAttach = create.Flag("attach", "Attach to the console if it starts successfully").
Bool()
createCommand = create.Arg("command", "Command to run in console").
Strings()
attach = cli.Command("attach", "Attach to a running console")
attachName = attach.Flag("name", "Console name").
Required().
String()
list = cli.Command("list", "List currently running consoles")
listUsername = list.Flag("user", "Kubernetes username. Not usually supplied, can be inferred from your gcloud login").
Short('u').
Default("").
String()
listSelector = list.Flag("selector", "Selector to match the console").
Short('s').
Default("").
String()
authorise = cli.Command("authorise", "Authorise a peer-reviewed console request")
authoriseUser = authorise.Flag("user", "Name of the user to attribute to verification. This must match the username that the Kubernetes API recognises you as").
String()
authoriseName = authorise.Flag("name", "Console to authorise").
Required().
String()
)
func main() {
// Set up logging
logger := kitlog.NewLogfmtLogger(os.Stderr)
logger = level.NewFilter(logger, level.AllowInfo())
// logger = kitlog.With(logger, "ts", kitlog.DefaultTimestampUTC, "caller", logging.RecorderAwareCaller())
stdlog.SetOutput(kitlog.NewStdlibAdapter(logger))
klog.SetOutput(kitlog.NewStdlibAdapter(logger))
ctx, _ := signals.SetupSignalHandler()
if err := Run(ctx, logger); err != nil && !errors.Is(err, context.Canceled) {
cli.Fatalf("unexpected error: %s", err)
}
}
// Run is the entrypoint for the cli application, after housekeeping tasks has been finished,
// e.g. setting up logging.
func Run(ctx context.Context, logger kitlog.Logger) error {
// Parse application args using kingpin
// This is done here to bind the flags without creating multiple global variables.
cmd := kingpin.MustParse(cli.Parse(os.Args[1:]))
config, err := newKubeConfig(*cliContext)
if err != nil {
return err
}
consoleRunner, err := runner.New(config)
if err != nil {
return err
}
// Match on the kingpin command and enter the main command
switch cmd {
case create.FullCommand():
_, err = consoleRunner.Create(
ctx,
runner.CreateOptions{
Namespace: *cliNamespace,
Selector: *createSelector,
Timeout: *createTimeout,
Reason: *createReason,
Command: *createCommand,
Attach: *createAttach,
Noninteractive: *createNoninteractive,
KubeConfig: config,
IO: runner.IOStreams{
In: os.Stdin,
Out: os.Stdout,
ErrOut: os.Stderr,
},
Hook: LifecyclePrinter(logger),
},
)
return err
case attach.FullCommand():
return consoleRunner.Attach(
ctx,
runner.AttachOptions{
Namespace: *cliNamespace,
KubeConfig: config,
Name: *attachName,
IO: runner.IOStreams{
In: os.Stdin,
Out: os.Stdout,
ErrOut: os.Stderr,
},
Hook: LifecyclePrinter(logger),
},
)
case list.FullCommand():
_, err = consoleRunner.List(
ctx,
runner.ListOptions{
Namespace: *cliNamespace,
Username: *listUsername,
Selector: *listSelector,
Output: os.Stdout,
},
)
return err
case authorise.FullCommand():
err = consoleRunner.Authorise(
ctx,
runner.AuthoriseOptions{
Namespace: *cliNamespace,
ConsoleName: *authoriseName,
Username: *authoriseUser,
},
)
}
return nil
}
// LifecyclePrinter hooks into console lifecycle events,
// reporting on the change of console phases during creation or attaching
func LifecyclePrinter(logger kitlog.Logger) runner.LifecycleHook {
return runner.DefaultLifecycleHook{
AttachingToPodFunc: func(csl *workloadsv1alpha1.Console) error {
logger.Log(
"msg", "Attaching to pod",
"console", csl.Name,
"namespace", csl.Namespace,
"pod", csl.Status.PodName,
)
return nil
},
ConsoleRequiresAuthorisationFunc: func(csl *workloadsv1alpha1.Console, rule *workloadsv1alpha1.ConsoleAuthorisationRule) error {
authoriserSlice := make([]string, 0, len(rule.ConsoleAuthorisers.Subjects))
for _, authoriser := range rule.ConsoleAuthorisers.Subjects {
authoriserSlice = append(authoriserSlice, authoriser.Kind+":"+authoriser.Name)
}
authorisers := strings.Join(authoriserSlice, ",")
logger.Log(
"msg", "Console requires authorisation",
"prompt", fmt.Sprintf("Please get a user from the list of authorisers to approve by running `theatre-consoles authorise --name %s --namespace %s --username {THEIR_USERNAME}`", csl.Name, csl.Namespace),
"authorisers", authorisers,
"console", csl.Name,
"namespace", csl.Namespace,
"pod", csl.Status.PodName,
)
return nil
},
ConsoleReadyFunc: func(csl *workloadsv1alpha1.Console) error {
logger.Log(
"msg", "Console is ready",
"console", csl.Name,
"namespace", csl.Namespace,
"pod", csl.Status.PodName,
)
return nil
},
ConsoleCreatedFunc: func(csl *workloadsv1alpha1.Console) error {
logger.Log(
"msg", "Console has been requested",
"console", csl.Name,
"namespace", csl.Namespace,
)
return nil
},
}
}
// newKubeConfig first tries using internal kubernetes configuration, and then falls back
// to ~/.kube/config
func newKubeConfig(kctx string) (*rest.Config, error) {
if config, err := rest.InClusterConfig(); err == nil {
return config, nil
}
config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
clientcmd.NewDefaultClientConfigLoadingRules(),
&clientcmd.ConfigOverrides{
CurrentContext: kctx,
},
).ClientConfig()
return config, err
}