Debian Codegraph @

api/v0/scheduler/scheduler.go

raw symbols SCIP
1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package scheduler
20
21 import (
22 "errors"
23 "fmt"
24 "math"
25 "math/rand"
26 "net"
27 "os/user"
28 "sync"
29 "sync/atomic"
30 "time"
31
32 "github.com/gogo/protobuf/proto"
33 log "github.com/golang/glog"
34 "github.com/mesos/mesos-go/api/v0/auth"
35 "github.com/mesos/mesos-go/api/v0/detector"
36 mesos "github.com/mesos/mesos-go/api/v0/mesosproto"
37 "github.com/mesos/mesos-go/api/v0/mesosproto/scheduler"
38 util "github.com/mesos/mesos-go/api/v0/mesosutil"
39 "github.com/mesos/mesos-go/api/v0/mesosutil/process"
40 "github.com/mesos/mesos-go/api/v0/messenger"
41 "github.com/mesos/mesos-go/api/v0/messenger/sessionid"
42 "github.com/mesos/mesos-go/api/v0/upid"
43 "github.com/pborman/uuid"
44 "golang.org/x/net/context"
45 )
46
47 const (
48 defaultAuthenticationTimeout = 30 * time.Second // timeout interval for an authentication attempt
49 registrationRetryIntervalMax = float64(1 * time.Minute)
50 registrationBackoffFactor = 2 * time.Second
51 )
52
53 var (
54 ErrDisconnected = errors.New("disconnected from mesos master")
55 errAuthenticationCanceled = errors.New("authentication canceled")
56 )
57
58 type ErrDriverAborted struct {
59 Reason string
60 }
61
62 func (err *ErrDriverAborted) Error() string {
63 if err.Reason != "" {
64 return err.Reason
65 }
66 return "driver-aborted"
67 }
68
69 // helper to track authentication progress and to prevent multiple close() ops
70 // against a signalling chan. it's safe to invoke the func's of this struct
71 // even if the receiver pointer is nil.
72 type authenticationAttempt struct {
73 done chan struct{}
74 doneOnce sync.Once
75 }
76
77 func (a *authenticationAttempt) cancel() {
78 if a != nil {
79 a.doneOnce.Do(func() { close(a.done) })
80 }
81 }
82
83 func (a *authenticationAttempt) inProgress() bool {
84 if a != nil {
85 select {
86 case <-a.done:
87 return false
88 default:
89 return true
90 }
91 }
92 return false
93 }
94
95 type DriverConfig struct {
96 Scheduler Scheduler
97 Framework *mesos.FrameworkInfo
98 Master string
99 Credential *mesos.Credential // optional
100 WithAuthContext func(context.Context) context.Context // required when Credential != nil
101 HostnameOverride string // optional
102 BindingAddress net.IP // optional
103 BindingPort uint16 // optional
104 PublishedAddress net.IP // optional
105 NewMessenger func() (messenger.Messenger, error) // optional
106 NewDetector func() (detector.Master, error) // optional
107 }
108
109 // Concrete implementation of a SchedulerDriver that connects a
110 // Scheduler with a Mesos master. The MesosSchedulerDriver is
111 // thread-safe.
112 //
113 // Note that scheduler failover is supported in Mesos. After a
114 // scheduler is registered with Mesos it may failover (to a new
115 // process on the same machine or across multiple machines) by
116 // creating a new driver with the ID given to it in
117 // Scheduler.Registered().
118 //
119 // The driver is responsible for invoking the Scheduler callbacks as
120 // it communicates with the Mesos master.
121 //
122 // Note that blocking on the MesosSchedulerDriver (e.g., via
123 // MesosSchedulerDriver.Join) doesn't affect the scheduler callbacks
124 // in anyway because they are handled by a different thread.
125 //
126 // TODO(yifan): examples.
127 // See src/examples/test_framework.cpp for an example of using the
128 // MesosSchedulerDriver.
129 type MesosSchedulerDriver struct {
130 masterPid *upid.UPID
131 frameworkInfo *mesos.FrameworkInfo
132 self *upid.UPID
133 stopCh chan struct{}
134 status mesos.Status
135 messenger messenger.Messenger
136 masterDetector detector.Master
137 connected bool
138 connection uuid.UUID
139 failoverTimeout float64
140 failover bool
141 cache *schedCache
142 updates map[string]*mesos.StatusUpdate // Key is a UUID string.
143 tasks map[string]*mesos.TaskInfo // Key is a UUID string.
144 credential *mesos.Credential
145 authenticated bool
146 authenticating *authenticationAttempt
147 reauthenticate bool
148 withAuthContext func(context.Context) context.Context
149 dispatch func(context.Context, *upid.UPID, proto.Message) error // send a message somewhere
150 started chan struct{} // signal chan that closes upon a successful call to Start()
151 eventLock sync.RWMutex // guard for all driver state
152 withScheduler func(f func(s Scheduler)) // execute some func with respect to the given scheduler; should be the last thing invoked in a handler (lock semantics)
153 done chan struct{} // signal chan that closes when no more events will be processed
154 }
155
156 // Create a new mesos scheduler driver with the given
157 // scheduler, framework info,
158 // master address, and credential(optional)
159 func NewMesosSchedulerDriver(config DriverConfig) (initializedDriver *MesosSchedulerDriver, err error) {
160 if config.Scheduler == nil {
161 err = fmt.Errorf("Scheduler callbacks required.")
162 } else if config.Master == "" {
163 err = fmt.Errorf("Missing master location URL.")
164 } else if config.Framework == nil {
165 err = fmt.Errorf("FrameworkInfo must be provided.")
166 } else if config.Credential != nil && config.WithAuthContext == nil {
167 err = fmt.Errorf("WithAuthContext must be provided when Credential != nil")
168 }
169 if err != nil {
170 return
171 }
172
173 framework := proto.Clone(config.Framework).(*mesos.FrameworkInfo)
174
175 // set default userid
176 if framework.GetUser() == "" {
177 user, err := user.Current()
178 if err != nil || user == nil {
179 if err != nil {
180 log.Warningf("Failed to obtain username: %v\n", err)
181 } else {
182 log.Warningln("Failed to obtain username.")
183 }
184 framework.User = proto.String("")
185 } else {
186 framework.User = proto.String(user.Username)
187 }
188 }
189
190 // default hostname
191 hostname := util.GetHostname(config.HostnameOverride)
192 if framework.GetHostname() == "" {
193 framework.Hostname = proto.String(hostname)
194 }
195
196 driver := &MesosSchedulerDriver{
197 frameworkInfo: framework,
198 stopCh: make(chan struct{}),
199 status: mesos.Status_DRIVER_NOT_STARTED,
200 cache: newSchedCache(),
201 credential: config.Credential,
202 failover: framework.Id != nil && len(framework.Id.GetValue()) > 0,
203 withAuthContext: config.WithAuthContext,
204 started: make(chan struct{}),
205 done: make(chan struct{}),
206 }
207
208 driver.withScheduler = driver.makeWithScheduler(config.Scheduler)
209
210 if framework.FailoverTimeout != nil && *framework.FailoverTimeout > 0 {
211 driver.failoverTimeout = *framework.FailoverTimeout * float64(time.Second)
212 log.V(1).Infof("found failover_timeout = %v", time.Duration(driver.failoverTimeout))
213 }
214
215 newDetector := config.NewDetector
216 if newDetector == nil {
217 newDetector = func() (detector.Master, error) {
218 return detector.New(config.Master)
219 }
220 }
221 newMessenger := config.NewMessenger
222 if newMessenger == nil {
223 newMessenger = func() (messenger.Messenger, error) {
224 process := process.New("scheduler")
225 return messenger.ForHostname(process, hostname, config.BindingAddress, config.BindingPort, config.PublishedAddress)
226 }
227 }
228
229 // initialize new detector.
230 if driver.masterDetector, err = newDetector(); err != nil {
231 return
232 } else if driver.messenger, err = newMessenger(); err != nil {
233 return
234 } else if err = driver.init(); err != nil {
235 return
236 } else {
237 initializedDriver = driver
238 }
239 return
240 }
241
242 func (driver *MesosSchedulerDriver) makeWithScheduler(cs Scheduler) func(func(Scheduler)) {
243 // mechanism that allows us to asynchronously invoke scheduler callbacks, but in a manner
244 // such that the callback invocations are serialized. useful because this will decouple the
245 // goroutine executing a messenger callback from the goroutine executing a scheduler callback,
246 // while preserving the serialization semantics for each type of callback handling.
247 // we use a chan to maintain the order of callback invocations; this is important for maintaining
248 // the order in which status updates are processed.
249 schedQueue := make(chan func(s Scheduler))
250 go func() {
251 defer func() {
252 close(driver.done)
253 log.V(1).Infoln("finished processing scheduler events")
254 }()
255 for f := range schedQueue {
256 f(cs)
257 }
258 }()
259
260 var schedLock sync.Mutex // synchronize write access to schedQueue
261 abort := int32(0)
262
263 // assume that when withScheduler is invoked eventLock is locked
264 return func(f func(s Scheduler)) {
265 const timeout = 1 * time.Second
266 t := time.NewTimer(timeout)
267 defer t.Stop()
268
269 trySend := func() (done bool) {
270 // don't block while attempting to enqueue a scheduler op; this could
271 // take a while depending upon the external scheduler implementation.
272 // also, it allows for multiple go-routines to re-compete for the lock
273 // every so often - this avoids indefinitely blocking a call to Abort().
274 driver.eventLock.Unlock()
275 schedLock.Lock()
276 defer func() {
277 schedLock.Unlock()
278 driver.eventLock.Lock()
279 }()
280
281 if atomic.LoadInt32(&abort) == 1 {
282 // can't send anymore
283 return true
284 }
285
286 // try to write to event queue...
287 select {
288 case schedQueue <- f:
289 done = true
290 case <-driver.stopCh:
291 done = true
292 case <-t.C:
293 }
294
295 // if stopping then close out the queue (keeping this check separate from
296 // the above on purpose! otherwise we could miss the close signal)
297 select {
298 case <-driver.stopCh:
299 if atomic.CompareAndSwapInt32(&abort, 0, 1) {
300 defer close(schedQueue)
301 log.V(1).Infoln("stopping scheduler event queue..")
302
303 // one last attempt, before we run out of time
304 select {
305 case schedQueue <- f:
306 case <-t.C:
307 }
308 }
309 default:
310 }
311 return
312 }
313 for !trySend() {
314 t.Reset(timeout) // TODO(jdef) add jitter to this
315 }
316 // have to do this outside trySend because here we're guarded by eventLock; it's ok
317 // if this happens more then once.
318 if atomic.LoadInt32(&abort) == 1 {
319 driver.withScheduler = func(f func(_ Scheduler)) {}
320 }
321 }
322 }
323
324 // ctx returns the current context.Context for the driver, expects to be invoked
325 // only when eventLock is locked.
326 func (driver *MesosSchedulerDriver) context() context.Context {
327 // set a "session" attribute so that the messenger can see it
328 // and use it for reporting delivery errors.
329 return sessionid.NewContext(context.TODO(), driver.connection.String())
330 }
331
332 // init initializes the driver.
333 func (driver *MesosSchedulerDriver) init() error {
334 log.Infof("Initializing mesos scheduler driver\n")
335 driver.dispatch = driver.messenger.Send
336
337 // serialize all callbacks from the messenger
338 type messageHandler func(context.Context, *upid.UPID, proto.Message)
339
340 guarded := func(h messageHandler) messenger.MessageHandler {
341 return messenger.MessageHandler(func(from *upid.UPID, msg proto.Message) {
342 driver.eventLock.Lock()
343 defer driver.eventLock.Unlock()
344 h(driver.context(), from, msg)
345 })
346 }
347
348 // Install handlers.
349 driver.messenger.Install(guarded(driver.frameworkRegistered), &mesos.FrameworkRegisteredMessage{})
350 driver.messenger.Install(guarded(driver.frameworkReregistered), &mesos.FrameworkReregisteredMessage{})
351 driver.messenger.Install(guarded(driver.resourcesOffered), &mesos.ResourceOffersMessage{})
352 driver.messenger.Install(guarded(driver.resourceOfferRescinded), &mesos.RescindResourceOfferMessage{})
353 driver.messenger.Install(guarded(driver.statusUpdated), &mesos.StatusUpdateMessage{})
354 driver.messenger.Install(guarded(driver.slaveLost), &mesos.LostSlaveMessage{})
355 driver.messenger.Install(guarded(driver.frameworkMessageRcvd), &mesos.ExecutorToFrameworkMessage{})
356 driver.messenger.Install(guarded(driver.frameworkErrorRcvd), &mesos.FrameworkErrorMessage{})
357 driver.messenger.Install(guarded(driver.exitedExecutor), &mesos.ExitedExecutorMessage{})
358 driver.messenger.Install(guarded(driver.handleMasterChanged), &mesos.InternalMasterChangeDetected{})
359 driver.messenger.Install(guarded(driver.handleAuthenticationResult), &mesos.InternalAuthenticationResult{})
360 driver.messenger.Install(guarded(driver.handleNetworkError), &mesos.InternalNetworkError{})
361 return nil
362 }
363
364 func (driver *MesosSchedulerDriver) handleNetworkError(_ context.Context, from *upid.UPID, pbMsg proto.Message) {
365 msg := pbMsg.(*mesos.InternalNetworkError)
366
367 if driver.status == mesos.Status_DRIVER_ABORTED {
368 log.Info("ignoring network error because the driver is aborted.")
369 return
370 } else if !from.Equal(driver.self) {
371 log.Errorf("ignoring network error because message received from upid '%v'", from)
372 return
373 } else if !driver.connected {
374 log.V(1).Infof("ignoring network error since we're not currently connected")
375 return
376 }
377
378 if driver.masterPid.String() == msg.GetPid() && driver.connection.String() == msg.GetSession() {
379 // fire a disconnection event
380 log.V(3).Info("Disconnecting scheduler.")
381
382 // need to set all 3 of these at once, since withScheduler() temporarily releases the lock and we don't
383 // want inconsistent connection facts
384 driver.masterPid = nil
385 driver.connected = false
386 driver.authenticated = false
387
388 driver.withScheduler(func(s Scheduler) { s.Disconnected(driver) })
389 log.Info("master disconnected")
390 }
391 }
392
393 // lead master detection callback.
394 func (driver *MesosSchedulerDriver) handleMasterChanged(_ context.Context, from *upid.UPID, pbMsg proto.Message) {
395 if driver.status == mesos.Status_DRIVER_ABORTED {
396 log.Info("Ignoring master change because the driver is aborted.")
397 return
398 } else if !from.Equal(driver.self) {
399 log.Errorf("ignoring master changed message received from upid '%v'", from)
400 return
401 }
402
403 // Reconnect every time a master is detected.
404 wasConnected := driver.connected
405 driver.connected = false
406 driver.authenticated = false
407
408 alertScheduler := false
409 if wasConnected {
410 log.V(3).Info("Disconnecting scheduler.")
411 driver.masterPid = nil
412 alertScheduler = true
413 }
414
415 msg := pbMsg.(*mesos.InternalMasterChangeDetected)
416 master := msg.Master
417
418 if master != nil {
419 log.Infof("New master %s detected\n", master.GetPid())
420
421 pid, err := upid.Parse(master.GetPid())
422 if err != nil {
423 panic("Unable to parse Master's PID value.") // this should not happen.
424 }
425
426 driver.masterPid = pid // save for downstream ops.
427 defer driver.tryAuthentication()
428 } else {
429 log.Infoln("No master detected.")
430 }
431 if alertScheduler {
432 driver.withScheduler(func(s Scheduler) { s.Disconnected(driver) })
433 }
434 }
435
436 // tryAuthentication expects to be guarded by eventLock
437 func (driver *MesosSchedulerDriver) tryAuthentication() {
438 if driver.authenticated {
439 // programming error
440 panic("already authenticated")
441 }
442
443 masterPid := driver.masterPid // save for referencing later in goroutine
444 if masterPid == nil {
445 log.Info("skipping authentication attempt because we lost the master")
446 return
447 }
448
449 if driver.authenticating.inProgress() {
450 // authentication is in progress, try to cancel it (we may too late already)
451 driver.authenticating.cancel()
452 driver.reauthenticate = true
453 return
454 }
455
456 if driver.credential != nil {
457 // authentication can block and we don't want to hold up the messenger loop
458 authenticating := &authenticationAttempt{done: make(chan struct{})}
459 go func() {
460 defer authenticating.cancel()
461 result := &mesos.InternalAuthenticationResult{
462 //TODO(jdef): is this really needed?
463 Success: proto.Bool(false),
464 Completed: proto.Bool(false),
465 Pid: proto.String(masterPid.String()),
466 }
467 // don't reference driver.authenticating here since it may have changed
468 if err := driver.authenticate(masterPid, authenticating); err != nil {
469 log.Errorf("Scheduler failed to authenticate: %v\n", err)
470 if err == auth.AuthenticationFailed {
471 result.Completed = proto.Bool(true)
472 }
473 } else {
474 result.Completed = proto.Bool(true)
475 result.Success = proto.Bool(true)
476 }
477 pid := driver.messenger.UPID()
478 driver.messenger.Route(context.TODO(), &pid, result)
479 }()
480 driver.authenticating = authenticating
481 } else {
482 log.Infoln("No credentials were provided. " +
483 "Attempting to register scheduler without authentication.")
484 driver.authenticated = true
485 go driver.doReliableRegistration(float64(registrationBackoffFactor))
486 }
487 }
488
489 func (driver *MesosSchedulerDriver) handleAuthenticationResult(_ context.Context, from *upid.UPID, pbMsg proto.Message) {
490 if driver.status != mesos.Status_DRIVER_RUNNING {
491 log.V(1).Info("ignoring authenticate because driver is not running")
492 return
493 }
494 if !from.Equal(driver.self) {
495 log.Errorf("ignoring authentication result message received from upid '%v'", from)
496 return
497 }
498 if driver.authenticated {
499 // programming error
500 panic("already authenticated")
501 }
502 if driver.masterPid == nil {
503 log.Infoln("ignoring authentication result because master is lost")
504 driver.authenticating.cancel() // cancel any in-progress background attempt
505
506 // disable future retries until we get a new master
507 driver.reauthenticate = false
508 return
509 }
510 msg := pbMsg.(*mesos.InternalAuthenticationResult)
511 if driver.reauthenticate || !msg.GetCompleted() || driver.masterPid.String() != msg.GetPid() {
512 log.Infof("failed to authenticate with master %v: master changed", driver.masterPid)
513 driver.authenticating.cancel() // cancel any in-progress background authentication
514 driver.reauthenticate = false
515 driver.tryAuthentication()
516 return
517 }
518 if !msg.GetSuccess() {
519 log.Errorf("master %v refused authentication", driver.masterPid)
520 return
521 }
522 driver.authenticated = true
523 go driver.doReliableRegistration(float64(registrationBackoffFactor))
524 }
525
526 // ------------------------- Accessors ----------------------- //
527
528 // Status returns the current driver status
529 func (driver *MesosSchedulerDriver) Status() mesos.Status {
530 driver.eventLock.RLock()
531 defer driver.eventLock.RUnlock()
532 return driver.status
533 }
534
535 // Running returns true if the driver is in the DRIVER_RUNNING state
536 func (driver *MesosSchedulerDriver) Running() bool {
537 driver.eventLock.RLock()
538 defer driver.eventLock.RUnlock()
539 return driver.status == mesos.Status_DRIVER_RUNNING
540 }
541
542 // Connected returns true if the driver has a registered (and authenticated, if enabled)
543 // connection to the leading mesos master
544 func (driver *MesosSchedulerDriver) Connected() bool {
545 driver.eventLock.RLock()
546 defer driver.eventLock.RUnlock()
547 return driver.connected
548 }
549
550 // stopped returns true if the driver status != DRIVER_RUNNING; expects to be guarded by eventLock
551 func (driver *MesosSchedulerDriver) stopped() bool {
552 return driver.status != mesos.Status_DRIVER_RUNNING
553 }
554
555 // ---------------------- Handlers for Events from Master --------------- //
556 func (driver *MesosSchedulerDriver) frameworkRegistered(_ context.Context, from *upid.UPID, pbMsg proto.Message) {
557 log.V(2).Infoln("Handling scheduler driver framework registered event.")
558
559 msg := pbMsg.(*mesos.FrameworkRegisteredMessage)
560 masterInfo := msg.GetMasterInfo()
561 masterPid := masterInfo.GetPid()
562 frameworkId := msg.GetFrameworkId()
563
564 if driver.status == mesos.Status_DRIVER_ABORTED {
565 log.Infof("ignoring FrameworkRegisteredMessage from master %s, driver is aborted", masterPid)
566 return
567 }
568
569 if driver.connected {
570 log.Infoln("ignoring FrameworkRegisteredMessage from master, driver is already connected", masterPid)
571 return
572 }
573
574 if driver.stopped() {
575 log.Infof("ignoring FrameworkRegisteredMessage from master %s, driver is stopped", masterPid)
576 return
577 }
578 if !driver.masterPid.Equal(from) {
579 log.Warningf("ignoring framework registered message because it was sent from '%v' instead of leading master '%v'", from, driver.masterPid)
580 return
581 }
582
583 log.Infof("Framework registered with ID=%s\n", frameworkId.GetValue())
584 driver.frameworkInfo.Id = frameworkId // generated by master.
585
586 driver.connected = true
587 driver.failover = false
588 driver.connection = uuid.NewUUID()
589 driver.withScheduler(func(s Scheduler) { s.Registered(driver, frameworkId, masterInfo) })
590 }
591
592 func (driver *MesosSchedulerDriver) frameworkReregistered(_ context.Context, from *upid.UPID, pbMsg proto.Message) {
593 log.V(1).Infoln("Handling Scheduler re-registered event.")
594 msg := pbMsg.(*mesos.FrameworkReregisteredMessage)
595
596 if driver.status == mesos.Status_DRIVER_ABORTED {
597 log.Infoln("Ignoring FrameworkReregisteredMessage from master, driver is aborted!")
598 return
599 }
600 if driver.connected {
601 log.Infoln("Ignoring FrameworkReregisteredMessage from master,driver is already connected!")
602 return
603 }
604 if !driver.masterPid.Equal(from) {
605 log.Warningf("ignoring framework re-registered message because it was sent from '%v' instead of leading master '%v'", from, driver.masterPid)
606 return
607 }
608
609 // TODO(vv) detect if message was from leading-master (sched.cpp)
610 log.Infof("Framework re-registered with ID [%s] ", msg.GetFrameworkId().GetValue())
611 driver.connected = true
612 driver.failover = false
613 driver.connection = uuid.NewUUID()
614
615 driver.withScheduler(func(s Scheduler) { s.Reregistered(driver, msg.GetMasterInfo()) })
616 }
617
618 func (driver *MesosSchedulerDriver) resourcesOffered(_ context.Context, from *upid.UPID, pbMsg proto.Message) {
619 log.V(2).Infoln("Handling resource offers.")
620
621 msg := pbMsg.(*mesos.ResourceOffersMessage)
622 if driver.status == mesos.Status_DRIVER_ABORTED {
623 log.Infoln("Ignoring ResourceOffersMessage, the driver is aborted!")
624 return
625 }
626
627 if !driver.connected {
628 log.Infoln("Ignoring ResourceOffersMessage, the driver is not connected!")
629 return
630 }
631
632 pidStrings := msg.GetPids()
633 if len(pidStrings) != len(msg.Offers) {
634 log.Errorln("Ignoring offers, Offer count does not match Slave PID count.")
635 return
636 }
637
638 for i, offer := range msg.Offers {
639 if pid, err := upid.Parse(pidStrings[i]); err == nil {
640 driver.cache.putOffer(offer, pid)
641 log.V(2).Infof("Cached offer %s from SlavePID %s", offer.Id.GetValue(), pid)
642 } else {
643 log.Warningf("Failed to parse offer PID '%v': %v", pid, err)
644 }
645 }
646
647 driver.withScheduler(func(s Scheduler) { s.ResourceOffers(driver, msg.Offers) })
648 }
649
650 func (driver *MesosSchedulerDriver) resourceOfferRescinded(_ context.Context, from *upid.UPID, pbMsg proto.Message) {
651 log.V(1).Infoln("Handling resource offer rescinded.")
652
653 msg := pbMsg.(*mesos.RescindResourceOfferMessage)
654
655 if driver.status == mesos.Status_DRIVER_ABORTED {
656 log.Infoln("Ignoring RescindResourceOfferMessage, the driver is aborted!")
657 return
658 }
659
660 if !driver.connected {
661 log.Infoln("Ignoring ResourceOffersMessage, the driver is not connected!")
662 return
663 }
664
665 // TODO(vv) check for leading master (see sched.cpp)
666
667 log.V(1).Infoln("Rescinding offer ", msg.OfferId.GetValue())
668 driver.cache.removeOffer(msg.OfferId)
669 driver.withScheduler(func(s Scheduler) { s.OfferRescinded(driver, msg.OfferId) })
670 }
671
672 func (driver *MesosSchedulerDriver) send(ctx context.Context, upid *upid.UPID, msg proto.Message) error {
673 c := make(chan error, 1)
674 go func() { c <- driver.dispatch(ctx, upid, msg) }()
675
676 select {
677 case <-ctx.Done():
678 <-c // wait for Send(...)
679 return ctx.Err()
680 case err := <-c:
681 return err
682 }
683 }
684
685 // statusUpdated expects to be guarded by eventLock
686 func (driver *MesosSchedulerDriver) statusUpdated(ctx context.Context, from *upid.UPID, pbMsg proto.Message) {
687 msg := pbMsg.(*mesos.StatusUpdateMessage)
688
689 if driver.status != mesos.Status_DRIVER_RUNNING {
690 log.V(1).Infoln("Ignoring StatusUpdate message, the driver is not running!")
691 return
692 }
693 if !from.Equal(driver.self) {
694 if !driver.connected {
695 log.V(1).Infoln("Ignoring StatusUpdate message, the driver is not connected!")
696 return
697 }
698 if !driver.masterPid.Equal(from) {
699 log.Warningf("ignoring status message because it was sent from '%v' instead of leading master '%v'", from, driver.masterPid)
700 return
701 }
702 }
703
704 log.V(2).Infof("Received status update from %q status source %q", from.String(), msg.GetPid())
705
706 status := msg.Update.GetStatus()
707
708 // see https://github.com/apache/mesos/blob/master/src/sched/sched.cpp#L887
709 // If the update does not have a 'uuid', it does not need
710 // acknowledging. However, prior to 0.23.0, the update uuid
711 // was required and always set. We also don't want to ACK updates
712 // that were internally generated. In 0.24.0, we can rely on the
713 // update uuid check here, until then we must still check for
714 // this being sent from the driver (from == UPID()) or from
715 // the master (pid == UPID()).
716 // TODO(vinod): Get rid of this logic in 0.25.0 because master
717 // and slave correctly set task status in 0.24.0.
718 if clearUUID := len(msg.Update.Uuid) == 0 || from.Equal(driver.self) || msg.GetPid() == driver.self.String(); clearUUID {
719 status.Uuid = nil
720 } else {
721 status.Uuid = msg.Update.Uuid
722 }
723
724 if driver.status == mesos.Status_DRIVER_ABORTED {
725 log.V(1).Infoln("Not sending StatusUpdate ACK, the driver is aborted!")
726 } else {
727
728 // Send StatusUpdate Acknowledgement; see above for the rules.
729 // Only send ACK if udpate was not from this driver and spec'd a UUID; this is compat w/ 0.23+
730 ackRequired := len(msg.Update.Uuid) > 0 && !from.Equal(driver.self) && msg.GetPid() != driver.self.String()
731 if ackRequired {
732 ackMsg := &mesos.StatusUpdateAcknowledgementMessage{
733 SlaveId: msg.Update.SlaveId,
734 FrameworkId: driver.frameworkInfo.Id,
735 TaskId: msg.Update.Status.TaskId,
736 Uuid: msg.Update.Uuid,
737 }
738
739 log.V(2).Infof("Sending ACK for status update %+v to %q", *msg.Update, from.String())
740 if err := driver.send(ctx, driver.masterPid, ackMsg); err != nil {
741 log.Errorf("Failed to send StatusUpdate ACK message: %v", err)
742 }
743 } else {
744 log.V(2).Infof("Not sending ACK, update is not from slave %q", from.String())
745 }
746 }
747 driver.withScheduler(func(s Scheduler) { s.StatusUpdate(driver, status) })
748 }
749
750 func (driver *MesosSchedulerDriver) exitedExecutor(_ context.Context, from *upid.UPID, pbMsg proto.Message) {
751 log.V(1).Infoln("Handling ExitedExceutor event.")
752 msg := pbMsg.(*mesos.ExitedExecutorMessage)
753
754 if driver.status == mesos.Status_DRIVER_ABORTED {
755 log.V(1).Infoln("Ignoring ExitedExecutor message, the driver is aborted!")
756 return
757 }
758 if !driver.connected {
759 log.V(1).Infoln("Ignoring ExitedExecutor message, the driver is not connected!")
760 return
761 }
762 status := msg.GetStatus()
763 log.V(2).Infoln("Lost executor %q from slave %q for framework %q with status %d",
764 msg.GetExecutorId().GetValue(),
765 msg.GetSlaveId().GetValue(),
766 msg.GetFrameworkId().GetValue(),
767 status)
768 driver.withScheduler(func(s Scheduler) { s.ExecutorLost(driver, msg.GetExecutorId(), msg.GetSlaveId(), int(status)) })
769 }
770
771 func (driver *MesosSchedulerDriver) slaveLost(_ context.Context, from *upid.UPID, pbMsg proto.Message) {
772 log.V(1).Infoln("Handling LostSlave event.")
773
774 msg := pbMsg.(*mesos.LostSlaveMessage)
775
776 if driver.status == mesos.Status_DRIVER_ABORTED {
777 log.V(1).Infoln("Ignoring LostSlave message, the driver is aborted!")
778 return
779 }
780
781 if !driver.connected {
782 log.V(1).Infoln("Ignoring LostSlave message, the driver is not connected!")
783 return
784 }
785
786 // TODO(VV) - detect leading master (see sched.cpp)
787
788 log.V(2).Infoln("Lost slave ", msg.SlaveId.GetValue())
789 driver.cache.removeSlavePid(msg.SlaveId)
790
791 driver.withScheduler(func(s Scheduler) { s.SlaveLost(driver, msg.SlaveId) })
792 }
793
794 func (driver *MesosSchedulerDriver) frameworkMessageRcvd(_ context.Context, from *upid.UPID, pbMsg proto.Message) {
795 log.V(1).Infoln("Handling framework message event.")
796
797 msg := pbMsg.(*mesos.ExecutorToFrameworkMessage)
798
799 if driver.status == mesos.Status_DRIVER_ABORTED {
800 log.V(1).Infoln("Ignoring framwork message, the driver is aborted!")
801 return
802 }
803
804 log.V(1).Infoln("Received Framwork Message ", msg.String())
805
806 driver.withScheduler(func(s Scheduler) { s.FrameworkMessage(driver, msg.ExecutorId, msg.SlaveId, string(msg.Data)) })
807 }
808
809 func (driver *MesosSchedulerDriver) frameworkErrorRcvd(ctx context.Context, from *upid.UPID, pbMsg proto.Message) {
810 log.V(1).Infoln("Handling framework error event.")
811 msg := pbMsg.(*mesos.FrameworkErrorMessage)
812 driver.fatal(ctx, msg.GetMessage())
813 }
814
815 // ---------------------- Interface Methods ---------------------- //
816
817 // Starts the scheduler driver.
818 // Returns immediately if an error occurs within start sequence.
819 func (driver *MesosSchedulerDriver) Start() (mesos.Status, error) {
820 driver.eventLock.Lock()
821 defer driver.eventLock.Unlock()
822 return driver.start()
823 }
824
825 // start expected to be guarded by eventLock
826 func (driver *MesosSchedulerDriver) start() (mesos.Status, error) {
827 select {
828 case <-driver.started:
829 return driver.status, errors.New("Unable to Start: driver has already been started once.")
830 default: // proceed
831 }
832
833 log.Infoln("Starting the scheduler driver...")
834
835 if driver.status != mesos.Status_DRIVER_NOT_STARTED {
836 return driver.status, fmt.Errorf("Unable to Start, expecting driver status %s, but is %s:", mesos.Status_DRIVER_NOT_STARTED, driver.status)
837 }
838
839 // Start the messenger.
840 if err := driver.messenger.Start(); err != nil {
841 log.Errorf("Scheduler failed to start the messenger: %v\n", err)
842 return driver.status, err
843 }
844
845 pid := driver.messenger.UPID()
846 driver.self = &pid
847 driver.status = mesos.Status_DRIVER_RUNNING
848 close(driver.started)
849
850 log.Infof("Mesos scheduler driver started with PID=%v", driver.self)
851
852 listener := detector.OnMasterChanged(func(m *mesos.MasterInfo) {
853 driver.messenger.Route(context.TODO(), driver.self, &mesos.InternalMasterChangeDetected{
854 Master: m,
855 })
856 })
857
858 if driver.masterDetector != nil {
859 // register with Detect() AFTER we have a self pid from the messenger, otherwise things get ugly
860 // because our internal messaging depends on it. detector callbacks are routed over the messenger
861 // bus, maintaining serial (concurrency-safe) callback execution.
862 log.V(1).Infof("starting master detector %T: %+v", driver.masterDetector, driver.masterDetector)
863 driver.masterDetector.Detect(listener)
864 log.V(2).Infoln("master detector started")
865 }
866 return driver.status, nil
867 }
868
869 // authenticate against the spec'd master pid using the configured authenticationProvider.
870 // the authentication process is canceled upon either cancelation of authenticating, or
871 // else because it timed out (see defaultAuthenticationTimeout, auth.Timeout).
872 //
873 // TODO(jdef) perhaps at some point in the future this will get pushed down into
874 // the messenger layer (e.g. to use HTTP-based authentication). We'd probably still
875 // specify the callback.Handler here, along with the user-selected authentication
876 // provider. Perhaps in the form of some messenger.AuthenticationConfig.
877 //
878 func (driver *MesosSchedulerDriver) authenticate(pid *upid.UPID, authenticating *authenticationAttempt) error {
879 log.Infof("authenticating with master %v", pid)
880
881 var (
882 authTimeout = defaultAuthenticationTimeout
883 ctx = driver.withAuthContext(context.TODO())
884 handler = &CredentialHandler{
885 pid: pid,
886 client: driver.self,
887 credential: driver.credential,
888 }
889 )
890
891 // check for authentication timeout override
892 if d, ok := auth.TimeoutFrom(ctx); ok {
893 authTimeout = d
894 }
895
896 ctx, cancel := context.WithTimeout(ctx, authTimeout)
897 ctx = auth.WithParentUPID(ctx, *driver.self)
898
899 ch := make(chan error, 1)
900 go func() { ch <- auth.Login(ctx, handler) }()
901
902 select {
903 case <-ctx.Done():
904 <-ch
905 return ctx.Err()
906 case <-authenticating.done:
907 cancel()
908 <-ch
909 return errAuthenticationCanceled
910 case e := <-ch:
911 cancel()
912 return e
913 }
914 }
915
916 func (driver *MesosSchedulerDriver) doReliableRegistration(maxBackoff float64) {
917 for {
918 if !driver.registerOnce() {
919 return
920 }
921 maxBackoff = math.Min(maxBackoff, registrationRetryIntervalMax)
922
923 // If failover timeout is present, bound the maximum backoff
924 // by 1/10th of the failover timeout.
925 if driver.failoverTimeout > 0 {
926 maxBackoff = math.Min(maxBackoff, driver.failoverTimeout/10.0)
927 }
928
929 // Determine the delay for next attempt by picking a random
930 // duration between 0 and 'maxBackoff' (jitter).
931 delay := time.Duration(maxBackoff * rand.Float64())
932
933 log.V(1).Infof("will retry registration in %v if necessary", delay)
934
935 t := time.NewTimer(delay)
936 defer t.Stop()
937
938 select {
939 case <-driver.stopCh:
940 return
941 case <-t.C:
942 maxBackoff *= 2
943 }
944 }
945 }
946
947 // registerOnce returns true if we should attempt another registration later; it is *not*
948 // guarded by eventLock: all access to mutable members of MesosSchedulerDriver should be
949 // explicitly synchronized.
950 func (driver *MesosSchedulerDriver) registerOnce() bool {
951 var (
952 failover bool
953 pid *upid.UPID
954 info *mesos.FrameworkInfo
955 ctx context.Context
956 )
957 if func() bool {
958 driver.eventLock.RLock()
959 defer driver.eventLock.RUnlock()
960
961 if driver.stopped() || driver.connected || driver.masterPid == nil || (driver.credential != nil && !driver.authenticated) {
962 log.V(1).Infof("skipping registration request: stopped=%v, connected=%v, authenticated=%v",
963 driver.stopped(), driver.connected, driver.authenticated)
964 return false
965 }
966 failover = driver.failover
967 pid = driver.masterPid
968 info = proto.Clone(driver.frameworkInfo).(*mesos.FrameworkInfo)
969 ctx = driver.context()
970 return true
971 }() {
972 // register framework
973 var message proto.Message
974 if len(info.GetId().GetValue()) > 0 {
975 // not the first time, or failing over
976 log.V(1).Infof("Reregistering with master: %v", pid)
977 message = &mesos.ReregisterFrameworkMessage{
978 Framework: info,
979 Failover: proto.Bool(failover),
980 }
981 } else {
982 log.V(1).Infof("Registering with master: %v", pid)
983 message = &mesos.RegisterFrameworkMessage{
984 Framework: info,
985 }
986 }
987 if err := driver.send(ctx, pid, message); err != nil {
988 log.Errorf("failed to send RegisterFramework message: %v", err)
989 if _, err = driver.Stop(failover); err != nil {
990 log.Errorf("failed to stop scheduler driver: %v", err)
991 }
992 }
993 return true
994 }
995 return false
996 }
997
998 //Join blocks until the driver is stopped.
999 //Should follow a call to Start()
1000 func (driver *MesosSchedulerDriver) Join() (mesos.Status, error) {
1001 driver.eventLock.Lock()
1002 defer driver.eventLock.Unlock()
1003 return driver.join()
1004 }
1005
1006 // join expects to be guarded by eventLock
1007 func (driver *MesosSchedulerDriver) join() (stat mesos.Status, err error) {
1008 if stat = driver.status; stat != mesos.Status_DRIVER_RUNNING {
1009 err = fmt.Errorf("Unable to Join, expecting driver status %s, but is %s", mesos.Status_DRIVER_RUNNING, stat)
1010 return
1011 }
1012
1013 timeout := 1 * time.Second
1014 t := time.NewTimer(timeout)
1015 defer t.Stop()
1016
1017 driver.eventLock.Unlock()
1018 defer func() {
1019 driver.eventLock.Lock()
1020 stat = driver.status
1021 }()
1022 waitForDeath:
1023 for {
1024 select {
1025 case <-driver.done:
1026 break waitForDeath
1027 case <-t.C:
1028 }
1029 t.Reset(timeout)
1030 }
1031 return
1032 }
1033
1034 //Run starts and joins driver process and waits to be stopped or aborted.
1035 func (driver *MesosSchedulerDriver) Run() (mesos.Status, error) {
1036 driver.eventLock.Lock()
1037 defer driver.eventLock.Unlock()
1038 return driver.run(driver.context())
1039 }
1040
1041 // run expected to be guarded by eventLock
1042 func (driver *MesosSchedulerDriver) run(ctx context.Context) (mesos.Status, error) {
1043 stat, err := driver.start()
1044
1045 if err != nil {
1046 return driver.stop(ctx, err, false)
1047 }
1048
1049 if stat != mesos.Status_DRIVER_RUNNING {
1050 return stat, fmt.Errorf("Unable to Run, expecting driver status %s, but is %s:", mesos.Status_DRIVER_RUNNING, driver.status)
1051 }
1052
1053 log.Infoln("Scheduler driver running. Waiting to be stopped.")
1054 return driver.join()
1055 }
1056
1057 //Stop stops the driver.
1058 func (driver *MesosSchedulerDriver) Stop(failover bool) (mesos.Status, error) {
1059 driver.eventLock.Lock()
1060 defer driver.eventLock.Unlock()
1061 return driver.stop(driver.context(), nil, failover)
1062 }
1063
1064 // stop expects to be guarded by eventLock
1065 func (driver *MesosSchedulerDriver) stop(ctx context.Context, cause error, failover bool) (mesos.Status, error) {
1066 log.Infoln("Stopping the scheduler driver")
1067 if stat := driver.status; stat != mesos.Status_DRIVER_RUNNING {
1068 return stat, fmt.Errorf("Unable to Stop, expected driver status %s, but is %s", mesos.Status_DRIVER_RUNNING, stat)
1069 }
1070
1071 if driver.connected && !failover {
1072 // unregister the framework
1073 log.Infoln("Unregistering the scheduler driver")
1074 message := &mesos.UnregisterFrameworkMessage{
1075 FrameworkId: driver.frameworkInfo.Id,
1076 }
1077 //TODO(jdef) this is actually a little racy: we send an 'unregister' message but then
1078 // immediately afterward the messenger is stopped in driver._stop(). so the unregister message
1079 // may not actually end up being sent out.
1080 if err := driver.send(ctx, driver.masterPid, message); err != nil {
1081 log.Errorf("Failed to send UnregisterFramework message while stopping driver: %v\n", err)
1082 if cause == nil {
1083 cause = &ErrDriverAborted{}
1084 }
1085 return driver._stop(cause, mesos.Status_DRIVER_ABORTED)
1086 }
1087 time.Sleep(2 * time.Second)
1088 }
1089
1090 // stop messenger
1091 return driver._stop(cause, mesos.Status_DRIVER_STOPPED)
1092 }
1093
1094 // stop expects to be guarded by eventLock
1095 func (driver *MesosSchedulerDriver) _stop(cause error, stopStatus mesos.Status) (mesos.Status, error) {
1096 // stop messenger
1097 defer func() {
1098 select {
1099 case <-driver.stopCh:
1100 return
1101 default:
1102 }
1103 close(driver.stopCh)
1104 // decouple to avoid deadlock (avoid nested withScheduler() invocations)
1105 go func() {
1106 driver.eventLock.Lock()
1107 defer driver.eventLock.Unlock()
1108 if cause != nil {
1109 log.V(1).Infof("Sending error via withScheduler: %v", cause)
1110 driver.withScheduler(func(s Scheduler) { s.Error(driver, cause.Error()) })
1111 } else {
1112 // send a noop func, withScheduler needs to see that stopCh is closed
1113 log.V(1).Infof("Sending kill signal to withScheduler")
1114 driver.withScheduler(func(_ Scheduler) {})
1115 }
1116 }()
1117 }()
1118 driver.status = stopStatus
1119 driver.connected = false
1120 driver.connection = uuid.UUID{}
1121
1122 log.Info("stopping messenger")
1123 err := driver.messenger.Stop()
1124
1125 log.Infof("Stop() complete with status %v error %v", stopStatus, err)
1126 return stopStatus, err
1127 }
1128
1129 func (driver *MesosSchedulerDriver) Abort() (stat mesos.Status, err error) {
1130 driver.eventLock.Lock()
1131 defer driver.eventLock.Unlock()
1132 return driver.abort(driver.context(), nil)
1133 }
1134
1135 // abort expects to be guarded by eventLock
1136 func (driver *MesosSchedulerDriver) abort(ctx context.Context, cause error) (stat mesos.Status, err error) {
1137 if driver.masterDetector != nil {
1138 defer driver.masterDetector.Cancel()
1139 }
1140
1141 log.Infof("Aborting framework [%+v]", driver.frameworkInfo.Id)
1142
1143 if driver.connected {
1144 _, err = driver.stop(ctx, cause, true)
1145 } else {
1146 driver._stop(cause, mesos.Status_DRIVER_ABORTED)
1147 }
1148
1149 stat = mesos.Status_DRIVER_ABORTED
1150 driver.status = stat
1151 return
1152 }
1153
1154 func (driver *MesosSchedulerDriver) AcceptOffers(offerIds []*mesos.OfferID, operations []*mesos.Offer_Operation, filters *mesos.Filters) (mesos.Status, error) {
1155 driver.eventLock.Lock()
1156 defer driver.eventLock.Unlock()
1157
1158 if stat := driver.status; stat != mesos.Status_DRIVER_RUNNING {
1159 return stat, fmt.Errorf("Unable to AcceptOffers, expected driver status %s, but got %s", mesos.Status_DRIVER_RUNNING, stat)
1160 }
1161
1162 ctx := driver.context()
1163 if !driver.connected {
1164 err := ErrDisconnected
1165 for _, operation := range operations {
1166 if *operation.Type == mesos.Offer_Operation_LAUNCH {
1167 // decouple lost task processing to avoid deadlock (avoid nested withScheduler() invocations)
1168 operation := operation
1169 go func() {
1170 driver.eventLock.Lock()
1171 defer driver.eventLock.Unlock()
1172
1173 for _, task := range operation.Launch.TaskInfos {
1174 driver.pushLostTask(ctx, task, err.Error())
1175 }
1176 }()
1177 }
1178 }
1179 log.Errorf("Failed to send LaunchTask message: %v\n", err)
1180 return driver.status, err
1181 }
1182
1183 okOperations := make([]*mesos.Offer_Operation, 0, len(operations))
1184
1185 for _, offerId := range offerIds {
1186 for _, operation := range operations {
1187 // Keep only the slave PIDs where we run tasks so we can send
1188 // framework messages directly.
1189 if !driver.cache.containsOffer(offerId) {
1190 log.Warningf("Attempting to accept offers with unknown offer %s\n", offerId.GetValue())
1191 continue
1192 }
1193
1194 // Validate
1195 switch *operation.Type {
1196 case mesos.Offer_Operation_LAUNCH:
1197 tasks := []*mesos.TaskInfo{}
1198 // Set TaskInfo.executor.framework_id, if it's missing.
1199 for _, task := range operation.Launch.TaskInfos {
1200 newTask := *task
1201 if newTask.Executor != nil && newTask.Executor.FrameworkId == nil {
1202 newTask.Executor.FrameworkId = driver.frameworkInfo.Id
1203 }
1204 tasks = append(tasks, &newTask)
1205 }
1206 for _, task := range tasks {
1207 if driver.cache.getOffer(offerId).offer.SlaveId.Equal(task.SlaveId) {
1208 // cache the tasked slave, for future communication
1209 pid := driver.cache.getOffer(offerId).slavePid
1210 driver.cache.putSlavePid(task.SlaveId, pid)
1211 } else {
1212 log.Warningf("Attempting to launch task %s with the wrong slaveId offer %s\n", task.TaskId.GetValue(), task.SlaveId.GetValue())
1213 }
1214 }
1215 operation.Launch.TaskInfos = tasks
1216 okOperations = append(okOperations, operation)
1217 case mesos.Offer_Operation_RESERVE:
1218 // Only send reserved resources
1219 filtered := util.FilterResources(operation.Reserve.Resources, func(res *mesos.Resource) bool { return res.Reservation != nil })
1220 operation.Reserve.Resources = filtered
1221 okOperations = append(okOperations, operation)
1222 case mesos.Offer_Operation_UNRESERVE:
1223 // Only send reserved resources
1224 filtered := util.FilterResources(operation.Unreserve.Resources, func(res *mesos.Resource) bool { return res.Reservation != nil })
1225 operation.Unreserve.Resources = filtered
1226 okOperations = append(okOperations, operation)
1227 case mesos.Offer_Operation_CREATE:
1228 // Only send reserved resources disks with volumes
1229 filtered := util.FilterResources(operation.Create.Volumes, func(res *mesos.Resource) bool {
1230 return res.Reservation != nil && res.Disk != nil && res.GetName() == "disk"
1231 })
1232 operation.Create.Volumes = filtered
1233 okOperations = append(okOperations, operation)
1234 case mesos.Offer_Operation_DESTROY:
1235 // Only send reserved resources disks with volumes
1236 filtered := util.FilterResources(operation.Destroy.Volumes, func(res *mesos.Resource) bool {
1237 return res.Reservation != nil && res.Disk != nil && res.GetName() == "disk"
1238 })
1239 operation.Destroy.Volumes = filtered
1240 okOperations = append(okOperations, operation)
1241 }
1242 }
1243
1244 driver.cache.removeOffer(offerId) // if offer
1245 }
1246
1247 // Accept Offers
1248 message := &scheduler.Call{
1249 FrameworkId: driver.frameworkInfo.Id,
1250 Type: scheduler.Call_ACCEPT.Enum(),
1251 Accept: &scheduler.Call_Accept{
1252 OfferIds: offerIds,
1253 Operations: okOperations,
1254 Filters: filters,
1255 },
1256 }
1257
1258 if err := driver.send(ctx, driver.masterPid, message); err != nil {
1259 for _, operation := range operations {
1260 if *operation.Type == mesos.Offer_Operation_LAUNCH {
1261 // decouple lost task processing to avoid deadlock (avoid nested withScheduler() invocations)
1262 operation := operation
1263 go func() {
1264 driver.eventLock.Lock()
1265 defer driver.eventLock.Unlock()
1266
1267 for _, task := range operation.Launch.TaskInfos {
1268 driver.pushLostTask(ctx, task, "Unable to launch tasks: "+err.Error())
1269 }
1270 }()
1271 }
1272 }
1273 log.Errorf("Failed to send LaunchTask message: %v\n", err)
1274 return driver.status, err
1275 }
1276
1277 return driver.status, nil
1278 }
1279
1280 func (driver *MesosSchedulerDriver) LaunchTasks(offerIds []*mesos.OfferID, tasks []*mesos.TaskInfo, filters *mesos.Filters) (mesos.Status, error) {
1281 driver.eventLock.Lock()
1282 defer driver.eventLock.Unlock()
1283
1284 if stat := driver.status; stat != mesos.Status_DRIVER_RUNNING {
1285 return stat, fmt.Errorf("Unable to LaunchTasks, expected driver status %s, but got %s", mesos.Status_DRIVER_RUNNING, stat)
1286 }
1287
1288 ctx := driver.context()
1289
1290 // Launch tasks
1291 if !driver.connected {
1292 log.Infoln("Ignoring LaunchTasks message, disconnected from master.")
1293 // decouple lost task processing to avoid deadlock (avoid nested withScheduler() invocations)
1294 err := ErrDisconnected
1295 go func() {
1296 driver.eventLock.Lock()
1297 defer driver.eventLock.Unlock()
1298
1299 // Send statusUpdate with status=TASK_LOST for each task.
1300 // See sched.cpp L#823
1301 for _, task := range tasks {
1302 driver.pushLostTask(ctx, task, err.Error())
1303 }
1304 }()
1305 return driver.status, err
1306 }
1307
1308 okTasks := make([]*mesos.TaskInfo, 0, len(tasks))
1309
1310 // Set TaskInfo.executor.framework_id, if it's missing.
1311 for _, task := range tasks {
1312 if task.Executor != nil && task.Executor.FrameworkId == nil {
1313 task.Executor.FrameworkId = driver.frameworkInfo.Id
1314 }
1315 okTasks = append(okTasks, task)
1316 }
1317
1318 for _, offerId := range offerIds {
1319 for _, task := range okTasks {
1320 // Keep only the slave PIDs where we run tasks so we can send
1321 // framework messages directly.
1322 if driver.cache.containsOffer(offerId) {
1323 if driver.cache.getOffer(offerId).offer.SlaveId.Equal(task.SlaveId) {
1324 // cache the tasked slave, for future communication
1325 pid := driver.cache.getOffer(offerId).slavePid
1326 driver.cache.putSlavePid(task.SlaveId, pid)
1327 } else {
1328 log.Warningf("Attempting to launch task %s with the wrong slaveId offer %s\n", task.TaskId.GetValue(), task.SlaveId.GetValue())
1329 }
1330 } else {
1331 log.Warningf("Attempting to launch task %s with unknown offer %s\n", task.TaskId.GetValue(), offerId.GetValue())
1332 }
1333 }
1334
1335 driver.cache.removeOffer(offerId) // if offer
1336 }
1337
1338 // launch tasks
1339 message := &mesos.LaunchTasksMessage{
1340 FrameworkId: driver.frameworkInfo.Id,
1341 OfferIds: offerIds,
1342 Tasks: okTasks,
1343 Filters: filters,
1344 }
1345
1346 if err := driver.send(ctx, driver.masterPid, message); err != nil {
1347 // decouple lost task processing to avoid deadlock (avoid nested withScheduler() invocations)
1348 go func() {
1349 driver.eventLock.Lock()
1350 defer driver.eventLock.Unlock()
1351
1352 for _, task := range tasks {
1353 driver.pushLostTask(ctx, task, "Unable to launch tasks: "+err.Error())
1354 }
1355 }()
1356 log.Errorf("Failed to send LaunchTask message: %v\n", err)
1357 return driver.status, err
1358 }
1359
1360 return driver.status, nil
1361 }
1362
1363 // pushLostTask expects to be guarded by eventLock
1364 func (driver *MesosSchedulerDriver) pushLostTask(ctx context.Context, taskInfo *mesos.TaskInfo, why string) {
1365 msg := &mesos.StatusUpdateMessage{
1366 Update: &mesos.StatusUpdate{
1367 FrameworkId: driver.frameworkInfo.Id,
1368 Status: &mesos.TaskStatus{
1369 TaskId: taskInfo.TaskId,
1370 State: mesos.TaskState_TASK_LOST.Enum(),
1371 Source: mesos.TaskStatus_SOURCE_MASTER.Enum(),
1372 Message: proto.String(why),
1373 Reason: mesos.TaskStatus_REASON_MASTER_DISCONNECTED.Enum(),
1374 },
1375 SlaveId: taskInfo.SlaveId,
1376 ExecutorId: taskInfo.Executor.ExecutorId,
1377 Timestamp: proto.Float64(float64(time.Now().Unix())),
1378 },
1379 Pid: proto.String(driver.self.String()),
1380 }
1381
1382 // put it on internal chanel
1383 // will cause handler to push to attached Scheduler
1384 driver.statusUpdated(ctx, driver.self, msg)
1385 }
1386
1387 func (driver *MesosSchedulerDriver) KillTask(taskId *mesos.TaskID) (mesos.Status, error) {
1388 driver.eventLock.Lock()
1389 defer driver.eventLock.Unlock()
1390
1391 if stat := driver.status; stat != mesos.Status_DRIVER_RUNNING {
1392 return stat, fmt.Errorf("Unable to KillTask, expecting driver status %s, but got %s", mesos.Status_DRIVER_RUNNING, stat)
1393 }
1394
1395 if !driver.connected {
1396 log.Infoln("Ignoring kill task message, disconnected from master.")
1397 return driver.status, ErrDisconnected
1398 }
1399
1400 message := &mesos.KillTaskMessage{
1401 FrameworkId: driver.frameworkInfo.Id,
1402 TaskId: taskId,
1403 }
1404
1405 if err := driver.send(driver.context(), driver.masterPid, message); err != nil {
1406 log.Errorf("Failed to send KillTask message: %v\n", err)
1407 return driver.status, err
1408 }
1409
1410 return driver.status, nil
1411 }
1412
1413 func (driver *MesosSchedulerDriver) RequestResources(requests []*mesos.Request) (mesos.Status, error) {
1414 driver.eventLock.Lock()
1415 defer driver.eventLock.Unlock()
1416
1417 if stat := driver.status; stat != mesos.Status_DRIVER_RUNNING {
1418 return stat, fmt.Errorf("Unable to RequestResources, expecting driver status %s, but got %s", mesos.Status_DRIVER_RUNNING, stat)
1419 }
1420
1421 if !driver.connected {
1422 log.Infoln("Ignoring request resource message, disconnected from master.")
1423 return driver.status, ErrDisconnected
1424 }
1425
1426 message := &mesos.ResourceRequestMessage{
1427 FrameworkId: driver.frameworkInfo.Id,
1428 Requests: requests,
1429 }
1430
1431 if err := driver.send(driver.context(), driver.masterPid, message); err != nil {
1432 log.Errorf("Failed to send ResourceRequest message: %v\n", err)
1433 return driver.status, err
1434 }
1435
1436 return driver.status, nil
1437 }
1438
1439 func (driver *MesosSchedulerDriver) DeclineOffer(offerId *mesos.OfferID, filters *mesos.Filters) (mesos.Status, error) {
1440 // NOTE: don't lock eventLock here because we're delegating to LaunchTasks() and that does it for us
1441 // launching an empty task list will decline the offer
1442 return driver.LaunchTasks([]*mesos.OfferID{offerId}, []*mesos.TaskInfo{}, filters)
1443 }
1444
1445 func (driver *MesosSchedulerDriver) ReviveOffers() (mesos.Status, error) {
1446 driver.eventLock.Lock()
1447 defer driver.eventLock.Unlock()
1448
1449 if stat := driver.status; stat != mesos.Status_DRIVER_RUNNING {
1450 return stat, fmt.Errorf("Unable to ReviveOffers, expecting driver status %s, but got %s", mesos.Status_DRIVER_RUNNING, stat)
1451 }
1452 if !driver.connected {
1453 log.Infoln("Ignoring revive offers message, disconnected from master.")
1454 return driver.status, ErrDisconnected
1455 }
1456
1457 message := &mesos.ReviveOffersMessage{
1458 FrameworkId: driver.frameworkInfo.Id,
1459 }
1460 if err := driver.send(driver.context(), driver.masterPid, message); err != nil {
1461 log.Errorf("Failed to send ReviveOffers message: %v\n", err)
1462 return driver.status, err
1463 }
1464
1465 return driver.status, nil
1466 }
1467
1468 func (driver *MesosSchedulerDriver) SendFrameworkMessage(executorId *mesos.ExecutorID, slaveId *mesos.SlaveID, data string) (mesos.Status, error) {
1469 driver.eventLock.Lock()
1470 defer driver.eventLock.Unlock()
1471
1472 if stat := driver.status; stat != mesos.Status_DRIVER_RUNNING {
1473 return stat, fmt.Errorf("Unable to SendFrameworkMessage, expecting driver status %s, but got %s", mesos.Status_DRIVER_RUNNING, stat)
1474 }
1475 if !driver.connected {
1476 log.Infoln("Ignoring send framework message, disconnected from master.")
1477 return driver.status, ErrDisconnected
1478 }
1479
1480 message := &mesos.FrameworkToExecutorMessage{
1481 SlaveId: slaveId,
1482 FrameworkId: driver.frameworkInfo.Id,
1483 ExecutorId: executorId,
1484 Data: []byte(data),
1485 }
1486 // Use list of cached slaveIds from previous offers.
1487 // Send frameworkMessage directly to cached slave, otherwise to master.
1488 if driver.cache.containsSlavePid(slaveId) {
1489 slavePid := driver.cache.getSlavePid(slaveId)
1490 if slavePid.Equal(driver.self) {
1491 return driver.status, nil
1492 }
1493 if err := driver.send(driver.context(), slavePid, message); err != nil {
1494 log.Errorf("Failed to send framework to executor message: %v\n", err)
1495 return driver.status, err
1496 }
1497 } else {
1498 // slavePid not cached, send to master.
1499 if err := driver.send(driver.context(), driver.masterPid, message); err != nil {
1500 log.Errorf("Failed to send framework to executor message: %v\n", err)
1501 return driver.status, err
1502 }
1503 }
1504
1505 return driver.status, nil
1506 }
1507
1508 func (driver *MesosSchedulerDriver) ReconcileTasks(statuses []*mesos.TaskStatus) (mesos.Status, error) {
1509 driver.eventLock.Lock()
1510 defer driver.eventLock.Unlock()
1511
1512 if stat := driver.status; stat != mesos.Status_DRIVER_RUNNING {
1513 return stat, fmt.Errorf("Unable to ReconcileTasks, expecting driver status %s, but got %s", mesos.Status_DRIVER_RUNNING, stat)
1514 }
1515 if !driver.connected {
1516 log.Infoln("Ignoring send Reconcile Tasks message, disconnected from master.")
1517 return driver.status, ErrDisconnected
1518 }
1519
1520 message := &mesos.ReconcileTasksMessage{
1521 FrameworkId: driver.frameworkInfo.Id,
1522 Statuses: statuses,
1523 }
1524 if err := driver.send(driver.context(), driver.masterPid, message); err != nil {
1525 log.Errorf("Failed to send reconcile tasks message: %v\n", err)
1526 return driver.status, err
1527 }
1528
1529 return driver.status, nil
1530 }
1531
1532 // error expects to be guarded by eventLock
1533 func (driver *MesosSchedulerDriver) fatal(ctx context.Context, err string) {
1534 if driver.status == mesos.Status_DRIVER_ABORTED {
1535 log.V(3).Infoln("Ignoring error message, the driver is aborted!")
1536 return
1537 }
1538 driver.abort(ctx, &ErrDriverAborted{Reason: err})
1539 }