Debian Codegraph @

api/v1/cmd/msh/msh.go

raw symbols SCIP
1 // msh is a minimal mesos v1 scheduler; it executes a shell command on a mesos agent.
2 package main
3
4 // Usage: msh {...command line args...}
5 //
6 // For example:
7 // msh -master 10.2.0.5:5050 -- ls -laF /tmp
8 //
9 // TODO: -gpu=1 to enable GPU_RESOURCES caps and request 1 gpu
10 //
11
12 import (
13 "bytes"
14 "context"
15 "flag"
16 "fmt"
17 "io"
18 "log"
19 "net"
20 "os"
21 "time"
22
23 "github.com/gogo/protobuf/proto"
24 "github.com/mesos/mesos-go/api/v1/lib"
25 "github.com/mesos/mesos-go/api/v1/lib/agent"
26 agentcalls "github.com/mesos/mesos-go/api/v1/lib/agent/calls"
27 "github.com/mesos/mesos-go/api/v1/lib/extras/scheduler/callrules"
28 "github.com/mesos/mesos-go/api/v1/lib/extras/scheduler/controller"
29 "github.com/mesos/mesos-go/api/v1/lib/extras/scheduler/eventrules"
30 "github.com/mesos/mesos-go/api/v1/lib/extras/scheduler/offers"
31 "github.com/mesos/mesos-go/api/v1/lib/extras/store"
32 "github.com/mesos/mesos-go/api/v1/lib/httpcli"
33 "github.com/mesos/mesos-go/api/v1/lib/httpcli/httpagent"
34 "github.com/mesos/mesos-go/api/v1/lib/httpcli/httpsched"
35 "github.com/mesos/mesos-go/api/v1/lib/resources"
36 "github.com/mesos/mesos-go/api/v1/lib/scheduler"
37 "github.com/mesos/mesos-go/api/v1/lib/scheduler/calls"
38 "github.com/mesos/mesos-go/api/v1/lib/scheduler/events"
39 )
40
41 const (
42 RFC3339a = "20060102T150405Z0700"
43 )
44
45 var (
46 FrameworkName = "msh"
47 TaskName = "msh"
48 MesosMaster = "127.0.0.1:5050"
49 User = "root"
50 Role = resources.Role("*")
51 CPUs = float64(0.010)
52 Memory = float64(64)
53
54 fidStore store.Singleton
55 declineAndSuppress bool
56 refuseSeconds = calls.RefuseSeconds(5 * time.Second)
57 wantsResources mesos.Resources
58 taskPrototype mesos.TaskInfo
59 interactive bool
60 tty bool
61 pod bool
62 executorPrototype mesos.ExecutorInfo
63 wantsExecutorResources = mesos.Resources{
64 resources.NewCPUs(0.01).Resource,
65 resources.NewMemory(32).Resource,
66 resources.NewDisk(5).Resource,
67 }
68 agentDirectory = make(map[mesos.AgentID]string)
69 uponExit = new(cleanups)
70 )
71
72 func init() {
73 flag.StringVar(&FrameworkName, "framework_name", FrameworkName, "Name of the framework")
74 flag.StringVar(&TaskName, "task_name", TaskName, "Name of the msh task")
75 flag.StringVar(&MesosMaster, "master", MesosMaster, "IP:port of the mesos master")
76 flag.StringVar(&User, "user", User, "OS user that owns the launched task")
77 flag.Float64Var(&CPUs, "cpus", CPUs, "CPU resources to allocate for the remote command")
78 flag.Float64Var(&Memory, "memory", Memory, "Memory resources to allocate for the remote command")
79 flag.BoolVar(&tty, "tty", tty, "Route all container stdio, stdout, stderr communication through a TTY device")
80 flag.BoolVar(&pod, "pod", pod, "Launch the remote command in a mesos task-group")
81 flag.BoolVar(&interactive, "interactive", interactive, "Attach to the task's stdin, stdout, and stderr")
82
83 fidStore = store.DecorateSingleton(
84 store.NewInMemorySingleton(),
85 store.DoSet().AndThen(func(_ store.Setter, v string, _ error) error {
86 log.Println("FrameworkID", v)
87 return nil
88 }))
89 }
90
91 func main() {
92 flag.Parse()
93 args := flag.Args()
94 if len(args) < 1 { // msh by itself prints usage
95 flag.Usage()
96 os.Exit(1)
97 }
98
99 wantsResources = mesos.Resources{
100 resources.NewCPUs(CPUs).Resource,
101 resources.NewMemory(Memory).Resource,
102 }
103 taskPrototype = mesos.TaskInfo{
104 Name: TaskName,
105 Command: &mesos.CommandInfo{
106 Value: proto.String(args[0]),
107 Shell: proto.Bool(false),
108 },
109 }
110 taskPrototype.Command.Arguments = args
111 if interactive {
112 taskPrototype.Container = &mesos.ContainerInfo{
113 Type: mesos.ContainerInfo_MESOS.Enum(),
114 TTYInfo: &mesos.TTYInfo{},
115 }
116 }
117 if term := os.Getenv("TERM"); term != "" && tty {
118 taskPrototype.Command.Environment = &mesos.Environment{
119 Variables: []mesos.Environment_Variable{
120 mesos.Environment_Variable{Name: "TERM", Value: &term},
121 },
122 }
123 }
124 if err := run(); err != nil {
125 if exitErr, ok := err.(ExitError); ok {
126 if code := int(exitErr); code != 0 {
127 log.Println(exitErr)
128 uponExit.unwind()
129 os.Exit(code)
130 }
131 // else, code=0 indicates success, exit normally
132 } else {
133 uponExit.unwind()
134 log.Fatalf("%#v", err)
135 }
136 }
137 uponExit.unwind()
138 }
139
140 func run() error {
141 var (
142 ctx, cancel = context.WithCancel(context.Background())
143 caller = callrules.WithFrameworkID(store.GetIgnoreErrors(fidStore)).Caller(buildClient())
144 )
145
146 return controller.Run(
147 ctx,
148 &mesos.FrameworkInfo{User: User, Name: FrameworkName, Role: (*string)(&Role)},
149 caller,
150 controller.WithEventHandler(buildEventHandler(caller)),
151 controller.WithFrameworkID(store.GetIgnoreErrors(fidStore)),
152 controller.WithSubscriptionTerminated(func(err error) {
153 defer cancel()
154 if err == io.EOF {
155 log.Println("disconnected")
156 }
157 }),
158 )
159 }
160
161 func buildClient() calls.Caller {
162 return httpsched.NewCaller(httpcli.New(
163 httpcli.Endpoint(fmt.Sprintf("http://%s/api/v1/scheduler", MesosMaster)),
164 ))
165 }
166
167 func buildEventHandler(caller calls.Caller) events.Handler {
168 logger := controller.LogEvents(nil)
169 return controller.LiftErrors().Handle(events.Handlers{
170 scheduler.Event_SUBSCRIBED: eventrules.Rules{
171 logger,
172 controller.TrackSubscription(fidStore, 0),
173 updateExecutor,
174 },
175
176 scheduler.Event_OFFERS: eventrules.Rules{
177 trackAgents,
178 maybeDeclineOffers(caller),
179 eventrules.DropOnError(),
180 eventrules.Handle(resourceOffers(caller)),
181 },
182
183 scheduler.Event_UPDATE: controller.AckStatusUpdates(caller).AndThen().HandleF(statusUpdate),
184 }.Otherwise(logger.HandleEvent))
185 }
186
187 func updateExecutor(ctx context.Context, e *scheduler.Event, err error, chain eventrules.Chain) (context.Context, *scheduler.Event, error) {
188 if err != nil {
189 return chain(ctx, e, err)
190 }
191 if e.GetType() != scheduler.Event_SUBSCRIBED {
192 return chain(ctx, e, err)
193 }
194 if pod {
195 executorPrototype = mesos.ExecutorInfo{
196 Type: mesos.ExecutorInfo_DEFAULT,
197 FrameworkID: e.GetSubscribed().FrameworkID,
198 }
199 }
200 return chain(ctx, e, err)
201 }
202
203 func trackAgents(ctx context.Context, e *scheduler.Event, err error, chain eventrules.Chain) (context.Context, *scheduler.Event, error) {
204 if err != nil {
205 return chain(ctx, e, err)
206 }
207 if e.GetType() != scheduler.Event_OFFERS {
208 return chain(ctx, e, err)
209 }
210 off := e.GetOffers().GetOffers()
211 for i := range off {
212 // TODO(jdef) eventually implement an algorithm to purge agents that are gone
213 agentDirectory[off[i].GetAgentID()] = off[i].GetHostname()
214 }
215 return chain(ctx, e, err)
216 }
217
218 func maybeDeclineOffers(caller calls.Caller) eventrules.Rule {
219 return func(ctx context.Context, e *scheduler.Event, err error, chain eventrules.Chain) (context.Context, *scheduler.Event, error) {
220 if err != nil {
221 return chain(ctx, e, err)
222 }
223 if e.GetType() != scheduler.Event_OFFERS || !declineAndSuppress {
224 return chain(ctx, e, err)
225 }
226 off := offers.Slice(e.GetOffers().GetOffers())
227 err = calls.CallNoData(ctx, caller, calls.Decline(off.IDs()...).With(refuseSeconds))
228 if err == nil {
229 // we shouldn't have received offers, maybe the prior suppress call failed?
230 err = calls.CallNoData(ctx, caller, calls.Suppress())
231 }
232 return ctx, e, err // drop
233 }
234 }
235
236 func resourceOffers(caller calls.Caller) events.HandlerFunc {
237 return func(ctx context.Context, e *scheduler.Event) (err error) {
238 var (
239 off = e.GetOffers().GetOffers()
240 index = offers.NewIndex(off, nil)
241 matchResources = func() mesos.Resources {
242 if pod {
243 return wantsResources.Plus(wantsExecutorResources...)
244 } else {
245 return wantsResources
246 }
247 }()
248 match = index.Find(offers.ContainsResources(matchResources))
249 )
250 if match != nil {
251 ts := time.Now().Format(RFC3339a)
252 task := taskPrototype
253 task.TaskID = mesos.TaskID{Value: ts}
254 task.AgentID = match.AgentID
255 task.Resources = resources.Find(
256 resources.Flatten(wantsResources, Role.Assign()),
257 match.Resources...,
258 )
259
260 if pod {
261 executor := executorPrototype
262 executor.ExecutorID = mesos.ExecutorID{Value: "msh_" + ts}
263 executor.Resources = resources.Find(
264 resources.Flatten(wantsExecutorResources, Role.Assign()),
265 match.Resources...,
266 )
267 err = calls.CallNoData(ctx, caller, calls.Accept(
268 calls.OfferOperations{calls.OpLaunchGroup(executor, task)}.WithOffers(match.ID),
269 ))
270 } else {
271 err = calls.CallNoData(ctx, caller, calls.Accept(
272 calls.OfferOperations{calls.OpLaunch(task)}.WithOffers(match.ID),
273 ))
274 }
275 if err != nil {
276 return
277 }
278
279 declineAndSuppress = true
280 } else {
281 log.Println("rejected insufficient offers")
282 }
283 // decline all but the possible match
284 delete(index, match.GetID())
285 err = calls.CallNoData(ctx, caller, calls.Decline(index.IDs()...).With(refuseSeconds))
286 if err != nil {
287 return
288 }
289 if declineAndSuppress {
290 err = calls.CallNoData(ctx, caller, calls.Suppress())
291 }
292 return
293 }
294 }
295
296 func statusUpdate(_ context.Context, e *scheduler.Event) error {
297 s := e.GetUpdate().GetStatus()
298 switch st := s.GetState(); st {
299 case mesos.TASK_FINISHED, mesos.TASK_RUNNING, mesos.TASK_STAGING, mesos.TASK_STARTING:
300 log.Printf("status update from agent %q: %v", s.GetAgentID().GetValue(), st)
301 if st == mesos.TASK_RUNNING && interactive && s.AgentID != nil {
302 cid := s.GetContainerStatus().GetContainerID()
303 if cid != nil {
304 log.Printf("attaching for interactive session to agent %q container %q", s.AgentID.Value, cid.Value)
305 return tryInteractive(agentDirectory[*s.AgentID], *cid)
306 }
307 }
308 if st != mesos.TASK_FINISHED {
309 return nil
310 }
311 case mesos.TASK_LOST, mesos.TASK_KILLED, mesos.TASK_FAILED, mesos.TASK_ERROR:
312 log.Println("Exiting because task " + s.GetTaskID().Value +
313 " is in an unexpected state " + st.String() +
314 " with reason " + s.GetReason().String() +
315 " from source " + s.GetSource().String() +
316 " with message '" + s.GetMessage() + "'")
317 return ExitError(3)
318 default:
319 log.Println("unexpected task state, aborting", st)
320 return ExitError(4)
321 }
322 return ExitError(0) // kind of ugly, but better than os.Exit(0)
323 }
324
325 type ExitError int
326
327 func (e ExitError) Error() string { return fmt.Sprintf("exit code %d", int(e)) }
328
329 func tryInteractive(agentHost string, cid mesos.ContainerID) (err error) {
330 // TODO(jdef) only re-attach if we're disconnected (guard against redundant TASK_RUNNING)
331 var (
332 ctx, cancel = context.WithCancel(context.TODO())
333 winCh <-chan mesos.TTYInfo_WindowSize
334 )
335 if tty {
336 ttyd, err := initTTY()
337 if err != nil {
338 cancel() // stop go-vet from complaining
339 return err
340 }
341
342 uponExit.push(ttyd.Close) // fail-safe
343
344 go func() {
345 <-ctx.Done()
346 //println("closing ttyd via ctx.Done")
347 ttyd.Close()
348 }()
349
350 winCh = ttyd.winch
351 }
352
353 var (
354 cli = httpagent.NewSender(
355 httpcli.New(
356 httpcli.Endpoint(fmt.Sprintf("http://%s/api/v1", net.JoinHostPort(agentHost, "5051"))),
357 ).Send,
358 )
359 aciCh = make(chan *agent.Call, 1) // must be buffered to avoid blocking below
360 )
361 aciCh <- agentcalls.AttachContainerInput(cid) // very first input message MUST be this
362 go func() {
363 defer cancel()
364 acif := agentcalls.FromChan(aciCh)
365
366 // blocking call, hence the goroutine; Send only returns when the input stream is severed
367 err2 := agentcalls.SendNoData(ctx, cli, acif)
368 if err2 != nil && err2 != io.EOF {
369 log.Printf("attached input stream error %v", err2)
370 }
371 }()
372
373 // attach to container stdout, stderr; Send returns immediately with a Response from which output
374 // may be decoded.
375 output, err := cli.Send(ctx, agentcalls.NonStreaming(agentcalls.AttachContainerOutput(cid)))
376 if err != nil {
377 log.Printf("attach output stream error: %v", err)
378 if output != nil {
379 output.Close()
380 }
381 cancel()
382 return
383 }
384
385 go func() {
386 defer cancel()
387 attachContainerOutput(output, os.Stdout, os.Stderr)
388 }()
389
390 go attachContainerInput(ctx, os.Stdin, winCh, aciCh)
391
392 return nil
393 }
394
395 func attachContainerInput(ctx context.Context, stdin io.Reader, winCh <-chan mesos.TTYInfo_WindowSize, aciCh chan<- *agent.Call) {
396 defer close(aciCh)
397
398 input := make(chan []byte)
399 go func() {
400 defer close(input)
401 escape := []byte{0x10, 0x11} // CTRL-P, CTRL-Q
402 var last byte
403 for {
404 buf := make([]byte, 512) // not efficient to always do this
405 n, err := stdin.Read(buf)
406 if n > 0 {
407 if (last == escape[0] && buf[0] == escape[1]) || bytes.Index(buf, escape) > -1 {
408 //println("escape sequence detected")
409 return
410 }
411 buf = buf[:n]
412 last = buf[n-1]
413 select {
414 case input <- buf:
415 case <-ctx.Done():
416 return
417 }
418 }
419 // TODO(jdef) check for temporary error?
420 if err != nil {
421 return
422 }
423 }
424 }()
425 for {
426 select {
427 case <-ctx.Done():
428 return
429 // TODO(jdef) send a heartbeat message every so often
430 // attach_container_input process_io heartbeats may act as keepalive's, `interval` field is ignored:
431 // https://github.com/apache/mesos/blob/4e200e55d8ed282b892f650983ebdf516680d90d/src/slave/containerizer/mesos/io/switchboard.cpp#L1608
432 case data, ok := <-input:
433 if !ok {
434 return
435 }
436 c := agentcalls.AttachContainerInputData(data)
437 select {
438 case aciCh <- c:
439 case <-ctx.Done():
440 return
441 }
442 case ws := <-winCh:
443 c := agentcalls.AttachContainerInputTTY(&mesos.TTYInfo{WindowSize: &ws})
444 select {
445 case aciCh <- c:
446 case <-ctx.Done():
447 return
448 }
449 }
450 }
451 }
452
453 func attachContainerOutput(resp mesos.Response, stdout, stderr io.Writer) error {
454 defer resp.Close()
455 forward := func(b []byte, out io.Writer) error {
456 n, err := out.Write(b)
457 if err == nil && len(b) != n {
458 err = io.ErrShortWrite
459 }
460 return err
461 }
462 for {
463 var pio agent.ProcessIO
464 err := resp.Decode(&pio)
465 if err != nil {
466 return err
467 }
468 switch pio.GetType() {
469 case agent.ProcessIO_DATA:
470 data := pio.GetData()
471 switch data.GetType() {
472 case agent.ProcessIO_Data_STDOUT:
473 if err := forward(data.GetData(), stdout); err != nil {
474 return err
475 }
476 case agent.ProcessIO_Data_STDERR:
477 if err := forward(data.GetData(), stderr); err != nil {
478 return err
479 }
480 default:
481 // ignore
482 }
483 default:
484 // ignore
485 }
486 }
487 }