This repository has been archived by the owner on Apr 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
291 lines (264 loc) · 6.88 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
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
package main
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"os"
"github.com/jessevdk/go-flags"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"gopkg.in/yaml.v3"
"github.com/bboozzoo/piled/pile/auth"
pb "github.com/bboozzoo/piled/pile/proto"
"github.com/bboozzoo/piled/utils"
)
type config struct {
Cert string `yaml:"cert"`
Key string `yaml:"key"`
CACert string `yaml:"ca-cert"`
Address string `yaml:"address"`
Token string `yaml:"token"`
}
type cmdStart struct {
MemoryMax string `long:"memory-max" description:"Max memory for this job"`
CPUMax string `long:"cpu-max" description:"Max CPU of this job"`
IOMax string `long:"io-max" description:"Max IO of this job"`
Positional struct {
Args []string `positional-arg-name:"arg" required:"1"`
} `positional-args:"yes"`
}
type cmdStop struct {
Positional struct {
ID string `positional-arg-name:"job-ID" required:"yes"`
} `positional-args:"yes"`
}
type cmdStatus struct {
Positional struct {
ID string `positional-arg-name:"job-ID" required:"yes"`
} `positional-args:"yes"`
}
type cmdOutput struct {
Positional struct {
ID string `positional-arg-name:"job-ID" required:"yes"`
} `positional-args:"yes"`
}
type commonMixin struct {
Config string `long:"config" description:"config file path" required:"yes"`
Address string `long:"address" description:"server address"`
Token string `long:"token" description:"authorization token"`
Debug bool `long:"debug"`
}
type options struct {
commonMixin
CmdStart cmdStart `command:"start"`
CmdStop cmdStop `command:"stop"`
CmdStatus cmdStatus `command:"status"`
CmdOutput cmdOutput `command:"output"`
}
var (
opts options
stdout io.Writer = os.Stdout
)
func parser() *flags.Parser {
p := flags.NewParser(&opts, flags.Default)
p.CommandHandler = func(command flags.Commander, args []string) error {
if opts.Debug {
logrus.SetLevel(logrus.TraceLevel)
}
return command.Execute(args)
}
return p
}
func main() {
p := parser()
_, err := p.ParseArgs(os.Args[1:])
if err != nil {
if utils.IsErrHelp(err) {
os.Exit(0)
}
os.Exit(1)
}
}
func loadConfig(from string) (*config, error) {
f, err := os.Open(from)
if err != nil {
return nil, err
}
defer f.Close()
d := yaml.NewDecoder(f)
var c config
if err := d.Decode(&c); err != nil {
return nil, err
}
logrus.Tracef("config: %+v", c)
if c.CACert == "" || c.Cert == "" || c.Key == "" {
return nil, fmt.Errorf("missing CA, certificate or key")
}
// fixup paths if not absolute
c.CACert = utils.FixupPathIfRelative(c.CACert, from)
c.Cert = utils.FixupPathIfRelative(c.Cert, from)
c.Key = utils.FixupPathIfRelative(c.Key, from)
return &c, nil
}
func (c *commonMixin) client() (conn *grpc.ClientConn, client pb.JobPileManagerClient, token string, err error) {
conf, err := loadConfig(c.Config)
if err != nil {
return nil, nil, "", fmt.Errorf("cannot load config: %v", err)
}
addr := conf.Address
if c.Address != "" {
addr = c.Address
}
if addr == "" {
return nil, nil, "", fmt.Errorf("cannot create client without an address")
}
token = conf.Token
if c.Token != "" {
token = c.Token
}
if token == "" {
return nil, nil, "", fmt.Errorf("cannot perform requests without a token")
}
cert, err := tls.LoadX509KeyPair(conf.Cert, conf.Key)
if err != nil {
return nil, nil, "", fmt.Errorf("cannot load server certificate: %v", err)
}
caCertBytes, err := os.ReadFile(conf.CACert)
if err != nil {
return nil, nil, "", fmt.Errorf("cannot read CA certificate: %v", err)
}
// very unlikely for the server cert of this demo to be signed by any
// CAs from the system pool, but let's use it anyway
pool, err := x509.SystemCertPool()
if err != nil {
return nil, nil, "", fmt.Errorf("cannot load system certificates pool: %v", err)
}
if !pool.AppendCertsFromPEM(caCertBytes) {
return nil, nil, "", fmt.Errorf("cannot add CA certificate")
}
creds := credentials.NewTLS(auth.ClientTLSConfig(auth.Config{
CAPool: pool,
Cert: cert,
}))
conn, err = grpc.Dial(addr,
grpc.WithTransportCredentials(creds))
if err != nil {
return nil, nil, "", fmt.Errorf("cannot connect: %w", err)
}
return conn, pb.NewJobPileManagerClient(conn), token, nil
}
func (c *cmdStart) Execute(args []string) error {
logrus.Tracef("start: %+v\n", c)
conn, jm, token, err := opts.client()
if err != nil {
return fmt.Errorf("cannot connect: %w", err)
}
defer conn.Close()
// TODO verify that args are indeed a valid command
js := pb.JobStartRequest{
Token: token,
Resources: &pb.Resources{
CPUMax: c.CPUMax,
MemoryMax: c.MemoryMax,
IOMax: c.IOMax,
},
Command: c.Positional.Args,
}
res, err := jm.Start(context.Background(), &js)
if err != nil {
return fmt.Errorf("cannot start job: %w", err)
}
fmt.Fprintln(stdout, res.ID)
return nil
}
func (c *cmdStop) Execute(args []string) error {
logrus.Tracef("stop: %+v\n", c)
// TODO verify that job ID looks sane
jobID := c.Positional.ID
conn, jm, token, err := opts.client()
if err != nil {
return fmt.Errorf("cannot connect: %w", err)
}
defer conn.Close()
jr := pb.JobRequest{
Token: token,
ID: jobID,
}
res, err := jm.Stop(context.Background(), &jr)
if err != nil {
return fmt.Errorf("cannot stop job: %w", err)
}
return printStatus(stdout, res.Status)
}
func printStatus(w io.Writer, status *pb.Status) error {
b := &bytes.Buffer{}
switch status.Status {
case pb.Status_ACTIVE:
b.WriteString("active")
case pb.Status_FAILED, pb.Status_OOM_KILLED:
label := "failed"
if status.Status == pb.Status_OOM_KILLED {
label = "oom-kill"
}
fmt.Fprintf(b, "%s (status=%v", label, status.ExitStatus)
if status.TermSignal != 0 {
fmt.Fprintf(b, ",signal=%v", status.TermSignal)
}
b.WriteRune(')')
case pb.Status_EXITED:
b.WriteString("exited")
default:
fmt.Fprintf(b, "<unknown %v>", status.Status)
}
b.WriteRune('\n')
_, err := w.Write(b.Bytes())
return err
}
func (c *cmdStatus) Execute(args []string) error {
jobID := c.Positional.ID
conn, jm, token, err := opts.client()
if err != nil {
return fmt.Errorf("cannot connect: %w", err)
}
defer conn.Close()
jr := pb.JobRequest{
Token: token,
ID: jobID,
}
res, err := jm.Status(context.Background(), &jr)
if err != nil {
return fmt.Errorf("cannot query job status: %w", err)
}
return printStatus(stdout, res.Status)
}
func (c *cmdOutput) Execute(args []string) error {
jobID := c.Positional.ID
conn, jm, token, err := opts.client()
if err != nil {
return fmt.Errorf("cannot connect: %w", err)
}
defer conn.Close()
jr := pb.JobRequest{
Token: token,
ID: jobID,
}
out, err := jm.Output(context.Background(), &jr)
if err != nil {
return fmt.Errorf("cannot obtain job output: %v", err)
}
for {
chunk, err := out.Recv()
if err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("cannot receive log chunk: %v", err)
}
stdout.Write(chunk.Chunk)
}
return nil
}