-
Notifications
You must be signed in to change notification settings - Fork 19
/
scheduler.go
1244 lines (1125 loc) · 34.8 KB
/
scheduler.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package scheduler
import (
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gogo/protobuf/proto"
log "github.com/golang/glog"
mesos "github.com/mesos/mesos-go/api/v0/mesosproto"
util "github.com/mesos/mesos-go/api/v0/mesosutil"
"github.com/mesos/mesos-go/api/v0/scheduler"
"github.com/samuel/go-zookeeper/zk"
"github.com/mesosphere/etcd-mesos/config"
"github.com/mesosphere/etcd-mesos/offercache"
"github.com/mesosphere/etcd-mesos/rpc"
)
const (
// portsPerTask: rpcPort, clientPort, httpPort
portsPerTask = 3
notReseeding = 0
reseedUnderway = 1
executorWantsCpus = 0.1
executorWantsMem = 32
executorWantsPorts = 1
)
// State represents the mutability of the scheduler.
type State int32
const (
// Mutable scheduler state occurs during:
// * starting up for the first time
// * growing (recovering) from 1 to N nodes
// * pruning dead nodes
// * exiting
Mutable State = iota
// Immutable scheduler state occurs during:
// * waiting for state to settle during initialization
// * disconnection from the Mesos master
// * performing a backup with the intention of seeding a new cluster
Immutable
)
type EtcdScheduler struct {
Stats Stats
Master string
ExecutorPath string
EtcdPath string
FrameworkName string
ZkConnect string
ZkChroot string
ZkServers []string
singleInstancePerSlave bool
desiredInstanceCount int
healthCheck func(map[string]*config.Node) error
shutdown func()
reconciliationInfoFunc func([]string, string, string) (map[string]string, error)
updateReconciliationInfoFunc func(map[string]string, []string, string, string) error
mut sync.RWMutex
state State
frameworkID *mesos.FrameworkID
masterInfo *mesos.MasterInfo
pending map[string]struct{}
running map[string]*config.Node
heardFrom map[string]struct{}
tasks map[string]*mesos.TaskID
highestInstanceID int64
executorUris []*mesos.CommandInfo_URI
offerCache *offercache.OfferCache
launchChan chan struct{}
diskPerTask float64
cpusPerTask float64
memPerTask float64
offerRefuseSeconds float64
pauseChan chan struct{}
chillSeconds time.Duration
autoReseedEnabled bool
reseedTimeout time.Duration
livelockWindow *time.Time
reseeding int32
reconciliationInfo map[string]string
}
type Stats struct {
RunningServers uint32 `json:"running_servers"`
LaunchedServers uint32 `json:"launched_servers"`
FailedServers uint32 `json:"failed_servers"`
ClusterLivelocks uint32 `json:"cluster_livelocks"`
ClusterReseeds uint32 `json:"cluster_reseeds"`
IsHealthy uint32 `json:"healthy"`
}
type OfferResources struct {
cpus float64
mems float64
disk float64
ports []*mesos.Value_Range
}
func NewEtcdScheduler(
desiredInstanceCount int,
chillSeconds int,
reseedTimeout int,
autoReseed bool,
executorUris []*mesos.CommandInfo_URI,
singleInstancePerSlave bool,
diskPerTask float64,
cpusPerTask float64,
memPerTask float64,
offerRefuseSeconds float64,
) *EtcdScheduler {
return &EtcdScheduler{
Stats: Stats{
IsHealthy: 1,
},
state: Immutable,
running: map[string]*config.Node{},
heardFrom: map[string]struct{}{},
pending: map[string]struct{}{},
tasks: map[string]*mesos.TaskID{},
highestInstanceID: time.Now().Unix(),
executorUris: executorUris,
ZkServers: []string{},
chillSeconds: time.Duration(chillSeconds),
autoReseedEnabled: autoReseed,
reseedTimeout: time.Second * time.Duration(reseedTimeout),
desiredInstanceCount: desiredInstanceCount,
launchChan: make(chan struct{}, 2048),
pauseChan: make(chan struct{}, 2048),
offerCache: offercache.New(
desiredInstanceCount,
singleInstancePerSlave,
),
healthCheck: rpc.HealthCheck,
shutdown: func() { os.Exit(1) },
reconciliationInfoFunc: rpc.GetPreviousReconciliationInfo,
updateReconciliationInfoFunc: rpc.UpdateReconciliationInfo,
singleInstancePerSlave: singleInstancePerSlave,
diskPerTask: diskPerTask,
cpusPerTask: cpusPerTask,
memPerTask: memPerTask,
offerRefuseSeconds: offerRefuseSeconds,
reconciliationInfo: map[string]string{},
}
}
// ----------------------- mesos callbacks ------------------------- //
func (s *EtcdScheduler) Registered(
driver scheduler.SchedulerDriver,
frameworkID *mesos.FrameworkID,
masterInfo *mesos.MasterInfo,
) {
log.Infoln("Framework Registered with Master ", masterInfo)
s.mut.Lock()
s.frameworkID = frameworkID
s.mut.Unlock()
if s.ZkConnect != "" {
err := rpc.PersistFrameworkID(
frameworkID,
s.ZkServers,
s.ZkChroot,
s.FrameworkName,
)
if err != nil && err != zk.ErrNodeExists {
log.Errorf("Failed to persist framework ID: %s", err)
if s.shutdown != nil {
s.shutdown()
}
} else if err == zk.ErrNodeExists {
log.Warning("Framework ID is already persisted for this cluster.")
}
}
s.Initialize(driver, masterInfo)
}
func (s *EtcdScheduler) Reregistered(
driver scheduler.SchedulerDriver,
masterInfo *mesos.MasterInfo,
) {
log.Infoln("Framework Reregistered with Master ", masterInfo)
s.Initialize(driver, masterInfo)
}
func (s *EtcdScheduler) Disconnected(scheduler.SchedulerDriver) {
log.Error("Mesos master disconnected.")
s.mut.Lock()
s.state = Immutable
s.mut.Unlock()
}
func (s *EtcdScheduler) ResourceOffers(
driver scheduler.SchedulerDriver,
offers []*mesos.Offer,
) {
var (
cpusWanted = s.cpusPerTask + executorWantsCpus
memWanted = s.memPerTask + executorWantsMem
portsWanted = uint64(portsPerTask + executorWantsPorts)
)
for _, offer := range offers {
resources := parseOffer(offer)
totalPorts := uint64(0)
for _, pr := range resources.ports {
totalPorts += (*pr.End + 1) - *pr.Begin
}
log.V(2).Infoln("Received Offer <", offer.Id.GetValue(),
"> with cpus=", resources.cpus,
" mem=", resources.mems,
" ports=", totalPorts,
" disk=", resources.disk,
" from slave ", *offer.SlaveId.Value)
s.mut.RLock()
if s.state == Immutable {
log.V(2).Info("Scheduler is Immutable. Declining received offer.")
s.decline(driver, offer)
s.mut.RUnlock()
continue
}
s.mut.RUnlock()
alreadyUsingSlave := false
for _, config := range s.RunningCopy() {
if config.SlaveID == offer.GetSlaveId().GetValue() {
alreadyUsingSlave = true
break
}
}
if alreadyUsingSlave {
log.V(2).Infoln("Already using this slave for etcd instance.")
if s.singleInstancePerSlave {
log.V(2).Infoln("Skipping offer.")
s.decline(driver, offer)
continue
}
log.V(2).Infoln("-single-instance-per-slave is false, continuing.")
}
if resources.cpus < cpusWanted {
log.V(1).Infoln("Offer cpu is insufficient.")
}
if resources.mems < memWanted {
log.V(1).Infoln("Offer memory is insufficient.")
}
if totalPorts < portsWanted {
log.V(1).Infoln("Offer ports are insuffient.")
}
if resources.disk < s.diskPerTask {
log.V(1).Infoln("Offer disk is insufficient.")
}
if resources.cpus >= cpusWanted &&
resources.mems >= memWanted &&
totalPorts >= portsWanted &&
resources.disk >= s.diskPerTask &&
s.offerCache.Push(offer) {
// golang for-loop variable reuse necessitates a copy here.
offerCpy := *offer
go func() {
time.Sleep(s.chillSeconds / 2 * time.Second)
// Decline the offer if we don't try to take it after a few seconds.
if s.offerCache.Rescind(offerCpy.Id) {
s.decline(driver, &offerCpy)
}
}()
log.V(2).Infoln("Added offer to offer cache.")
s.QueueLaunchAttempt()
} else {
s.decline(driver, offer)
log.V(2).Infoln("Offer rejected.")
}
}
}
func (s *EtcdScheduler) StatusUpdate(
driver scheduler.SchedulerDriver,
status *mesos.TaskStatus,
) {
s.mut.Lock()
defer s.mut.Unlock()
log.Infoln(
"Status update: task",
status.TaskId.GetValue(),
" is in state ",
status.State.Enum().String(),
)
node, err := config.Parse(status.GetTaskId().GetValue())
if err != nil {
log.Errorf("scheduler: failed to unmarshal config.Node from TaskId: %s", err)
return
}
node.SlaveID = status.SlaveId.GetValue()
// record that we've heard about this task
s.heardFrom[status.GetTaskId().GetValue()] = struct{}{}
switch status.GetState() {
case mesos.TaskState_TASK_LOST,
mesos.TaskState_TASK_FINISHED,
mesos.TaskState_TASK_KILLED,
mesos.TaskState_TASK_ERROR,
mesos.TaskState_TASK_FAILED:
log.Errorf("Task contraction: %+v", status.GetState())
log.Errorf("message: %s", status.GetMessage())
log.Errorf("reason: %+v", status.GetReason())
atomic.AddUint32(&s.Stats.FailedServers, 1)
// TODO(tyler) kill this
// Pump the brakes so that we have time to deconfigure the lost node
// before adding a new one. If we don't deconfigure first, we risk
// split brain.
s.PumpTheBrakes()
// now we know this task is dead
delete(s.pending, node.Name)
delete(s.running, node.Name)
delete(s.tasks, node.Name)
// We don't have to clean up the state in ZK for this
// as it is fine to eventually just persist when we
// receive a new TASK_RUNNING below.
delete(s.reconciliationInfo, status.TaskId.GetValue())
s.QueueLaunchAttempt()
// TODO(tyler) do we want to lock if the first task fails?
// TODO(tyler) can we handle a total loss at reconciliation time,
// when s.state == Immutable?
if len(s.running) == 0 && s.state == Mutable {
log.Error("TOTAL CLUSTER LOSS! LOCKING SCHEDULER, " +
"FOLLOW RESTORATION GUIDE AT " +
"https://github.com/mesosphere/" +
"etcd-mesos/blob/master/docs/response.md")
s.state = Immutable
}
case mesos.TaskState_TASK_STARTING:
case mesos.TaskState_TASK_RUNNING:
// We update data to ZK synchronously because it must happen
// in-order. If we spun off a goroutine this would possibly retry
// and succeed in the wrong order, and older data would win.
// We keep this simple here, as if ZK is healthy this won't take long.
// If this takes long, we're probably about to die anyway, as ZK is
// displeased and mesos-go will panic when it loses contact.
s.reconciliationInfo[status.TaskId.GetValue()] = status.SlaveId.GetValue()
err = s.updateReconciliationInfoFunc(
s.reconciliationInfo,
s.ZkServers,
s.ZkChroot,
s.FrameworkName,
)
if err != nil {
log.Errorf("Failed to persist reconciliation info: %+v", err)
}
delete(s.pending, node.Name)
_, present := s.running[node.Name]
if !present {
s.running[node.Name] = node
s.tasks[node.Name] = status.TaskId
}
// During reconcilliation, we may find nodes with higher ID's due to ntp drift
etcdIndexParts := strings.Split(node.Name, "-")
if len(etcdIndexParts) != 2 {
log.Warning("Task has a Name that does not follow the form etcd-<index>")
} else {
etcdIndex, err := strconv.ParseInt(etcdIndexParts[1], 10, 64)
if err != nil {
log.Warning("Task has a Name that does not follow the form etcd-<index>")
} else {
if etcdIndex > s.highestInstanceID {
s.highestInstanceID = etcdIndex + 1
}
}
}
default:
log.Warningf("Received unhandled task state: %+v", status.GetState())
}
}
func (s *EtcdScheduler) OfferRescinded(
driver scheduler.SchedulerDriver,
offerID *mesos.OfferID,
) {
log.Info("received OfferRescinded rpc")
s.offerCache.Rescind(offerID)
}
func (s *EtcdScheduler) FrameworkMessage(
driver scheduler.SchedulerDriver,
exec *mesos.ExecutorID,
slave *mesos.SlaveID,
msg string,
) {
log.Info("received framework message: %s", msg)
}
func (s *EtcdScheduler) SlaveLost(
scheduler.SchedulerDriver,
*mesos.SlaveID,
) {
log.Info("received slave lost rpc")
}
func (s *EtcdScheduler) ExecutorLost(
scheduler.SchedulerDriver,
*mesos.ExecutorID,
*mesos.SlaveID,
int,
) {
log.Info("received executor lost rpc")
}
func (s *EtcdScheduler) Error(driver scheduler.SchedulerDriver, err string) {
log.Infoln("Scheduler received error:", err)
if err == "Completed framework attempted to re-register" {
rpc.ClearZKState(s.ZkServers, s.ZkChroot, s.FrameworkName)
log.Error(
"Removing reference to completed " +
"framework in zookeeper and dying.",
)
if s.shutdown != nil {
s.shutdown()
}
}
}
// ----------------------- helper functions ------------------------- //
// decline declines an offer.
func (s *EtcdScheduler) decline(
driver scheduler.SchedulerDriver,
offer *mesos.Offer,
) {
log.V(2).Infof("Declining offer %s.", offer.Id.GetValue())
driver.DeclineOffer(
offer.Id,
&mesos.Filters{
// Decline offers for configured interval.
RefuseSeconds: proto.Float64(s.offerRefuseSeconds),
},
)
}
// RunningCopy makes a copy of the running map to minimize time
// spent with the scheduler lock is minimized.
func (s *EtcdScheduler) RunningCopy() map[string]*config.Node {
s.mut.RLock()
defer s.mut.RUnlock()
runningCopy := map[string]*config.Node{}
for k, v := range s.running {
runningCopy[k] = v
}
return runningCopy
}
func (s *EtcdScheduler) Initialize(
driver scheduler.SchedulerDriver,
masterInfo *mesos.MasterInfo,
) {
// Reset mutable state
s.mut.Lock()
s.running = map[string]*config.Node{}
s.heardFrom = map[string]struct{}{}
s.reconciliationInfo = map[string]string{}
s.masterInfo = masterInfo
s.mut.Unlock()
go s.attemptMasterSync(driver)
}
func (s *EtcdScheduler) attemptMasterSync(driver scheduler.SchedulerDriver) {
// Request that the master send us TaskStatus for live tasks.
backoff := 1
for retries := 0; retries < 5; retries++ {
previousReconciliationInfo, err := s.reconciliationInfoFunc(
s.ZkServers,
s.ZkChroot,
s.FrameworkName,
)
if err == nil {
s.mut.Lock()
s.reconciliationInfo = previousReconciliationInfo
s.mut.Unlock()
statuses := []*mesos.TaskStatus{}
for taskID, slaveID := range previousReconciliationInfo {
statuses = append(statuses, &mesos.TaskStatus{
SlaveId: util.NewSlaveID(slaveID),
TaskId: util.NewTaskID(taskID),
State: mesos.TaskState_TASK_RUNNING.Enum(),
})
}
// Here we do both implicit and explicit task reconciliation
// in the off-chance that we were unable to persist a running
// task in ZK after it started.
_, err = driver.ReconcileTasks([]*mesos.TaskStatus{})
if err != nil {
log.Errorf("Error while calling ReconcileTasks: %s", err)
continue
}
_, err = driver.ReconcileTasks(statuses)
if err != nil {
log.Errorf("Error while calling ReconcileTasks: %s", err)
} else {
// We want to allow some time for reconciled updates to arrive.
err := s.waitForMasterSync()
if err != nil {
log.Error(err)
} else {
s.mut.Lock()
log.Info("Scheduler transitioning to Mutable state.")
s.state = Mutable
s.mut.Unlock()
return
}
}
} else {
log.Error(err)
}
time.Sleep(time.Duration(backoff) * time.Second)
backoff = int(math.Min(float64(backoff<<1), 8))
}
log.Error("Failed to synchronize with master! " +
"It is dangerous to continue at this point. Dying.")
if s.shutdown != nil {
s.shutdown()
}
}
func (s *EtcdScheduler) isInSync() bool {
// TODO(tyler) clean up rpc.GetPeersFromState!
s.mut.RLock()
defer s.mut.RUnlock()
log.V(2).Info("Determining whether we're in-sync with the master by " +
"ensuring that we've heard about all previous tasks.")
log.V(2).Infof("running: %+v", s.running)
log.V(2).Infof("heardFrom: %+v", s.heardFrom)
log.V(2).Infof("reconciliationInfo: %+v", s.reconciliationInfo)
for taskID := range s.reconciliationInfo {
_, present := s.heardFrom[taskID]
if !present {
return false
}
}
return true
}
func (s *EtcdScheduler) waitForMasterSync() error {
backoff := 1
for retries := 0; retries < 5; retries++ {
log.Info("Trying to sync with master.")
if s.masterInfo == nil || s.masterInfo.Hostname == nil {
return errors.New("No master info.")
}
// TODO(tyler) clean up StateFunc stuff elsewhere!!
if s.isInSync() {
log.Info("Scheduler synchronized with master.")
return nil
} else {
log.Warning("Scheduler not yet in sync with master.")
}
time.Sleep(time.Duration(backoff) * time.Second)
backoff = int(math.Min(float64(backoff<<1), 8))
}
return errors.New("Unable to sync with master.")
}
func (s *EtcdScheduler) QueueLaunchAttempt() {
select {
case s.launchChan <- struct{}{}:
default:
// Somehow launchChan is full...
log.Warning("launchChan is full!")
}
}
func (s *EtcdScheduler) PumpTheBrakes() {
select {
case s.pauseChan <- struct{}{}:
default:
log.Warning("pauseChan is full!")
}
}
// Perform implicit reconciliation every 5 minutes
func (s *EtcdScheduler) PeriodicReconciler(driver scheduler.SchedulerDriver) {
for {
s.mut.RLock()
state := s.state
s.mut.RUnlock()
if state == Mutable {
_, err := driver.ReconcileTasks([]*mesos.TaskStatus{})
if err != nil {
log.Errorf("Error while calling ReconcileTasks: %s", err)
}
}
time.Sleep(5 * time.Minute)
}
}
func (s *EtcdScheduler) PeriodicHealthChecker() {
for {
time.Sleep(5 * s.chillSeconds * time.Second)
nodes := s.RunningCopy()
atomic.StoreUint32(&s.Stats.RunningServers, uint32(len(nodes)))
if len(nodes) == 0 {
atomic.StoreUint32(&s.Stats.IsHealthy, 0)
continue
}
err := s.healthCheck(nodes)
if err != nil {
atomic.StoreUint32(&s.Stats.IsHealthy, 0)
} else {
atomic.StoreUint32(&s.Stats.IsHealthy, 1)
}
}
}
func (s *EtcdScheduler) PeriodicLaunchRequestor() {
for {
s.mut.RLock()
log.Infof(
"running instances: %d desired: %d offers: %d",
len(s.running), s.desiredInstanceCount, s.offerCache.Len(),
)
atomic.StoreUint32(&s.Stats.RunningServers, uint32(len(s.running)))
if len(s.running) < s.desiredInstanceCount &&
s.state == Mutable {
s.QueueLaunchAttempt()
} else if s.state == Immutable {
log.Info("PeriodicLaunchRequestor skipping due to " +
"Immutable scheduler state.")
}
s.mut.RUnlock()
time.Sleep(5 * s.chillSeconds * time.Second)
}
}
func (s *EtcdScheduler) Prune() error {
s.mut.RLock()
defer s.mut.RUnlock()
if s.state == Mutable {
configuredMembers, err := rpc.MemberList(s.running)
if err != nil {
log.Errorf("Prune could not retrieve current member list: %s",
err)
return err
} else {
for k := range configuredMembers {
_, present := s.running[k]
if !present {
_, pending := s.pending[k]
if !pending {
log.Warningf("Prune attempting to deconfigure unknown etcd "+
"instance: %s", k)
if err := rpc.RemoveInstance(s.running, k); err != nil {
log.Errorf("Failed to remove instance: %s", err)
} else {
return nil
}
}
}
}
}
} else {
log.Info("Prune skipping due to Immutable scheduler state.")
}
return nil
}
// SerialLauncher performs the launching of all tasks in a time-limited
// way. This helps to prevent misconfiguration by allowing time for state
// to propagate.
func (s *EtcdScheduler) SerialLauncher(driver scheduler.SchedulerDriver) {
for {
// pauseChan needs priority over launchChan, so we need to try it
// before randomly selecting from either of them below.
for {
select {
case <-s.pauseChan:
log.V(2).Infof("SerialLauncher sleeping for %d seconds "+
"after receiving pause signal.", s.chillSeconds)
time.Sleep(s.chillSeconds * time.Second)
default:
goto FCFSPauseOrLaunch
}
}
FCFSPauseOrLaunch:
select {
case _, ok := <-s.launchChan:
if !ok {
return
}
s.launchOne(driver)
// Wait some time between launches to allow a cluster to settle.
log.V(2).Infof("SerialLauncher sleeping for %d seconds after "+
"launch attempt.", s.chillSeconds)
time.Sleep(s.chillSeconds * time.Second)
case <-s.pauseChan:
log.V(2).Infof("SerialLauncher sleeping for %d seconds "+
"after receiving pause signal.", s.chillSeconds)
time.Sleep(s.chillSeconds * time.Second)
}
}
}
func (s *EtcdScheduler) shouldLaunch(driver scheduler.SchedulerDriver) bool {
s.mut.RLock()
defer s.mut.RUnlock()
if s.state != Mutable {
log.Infoln("Scheduler is not mutable. Not launching a task.")
return false
}
if atomic.LoadInt32(&s.reseeding) == reseedUnderway {
log.Infoln("Currently reseeding, not launching a task.")
return false
}
if len(s.pending) != 0 {
log.Infoln("Waiting on pending task to fail or submit status. " +
"Not launching until we hear back.")
return false
}
log.V(2).Infof("running: %+v", s.running)
if len(s.running) >= s.desiredInstanceCount {
log.V(2).Infoln("Already running enough tasks.")
return false
}
members, err := rpc.MemberList(s.running)
if err != nil {
log.Errorf("Failed to retrieve running member list, "+
"rescheduling launch attempt for later: %s", err)
return false
}
if len(members) == s.desiredInstanceCount {
log.Errorf("Cluster is already configured for desired number of nodes. " +
"Must deconfigure any dead nodes first or we may risk livelock.")
return false
}
// Ensure we can reach ZK. This is already being done implicitly in
// the mesos-go driver, but it's not a bad thing to be pessimistic here.
_, err = s.reconciliationInfoFunc(
s.ZkServers,
s.ZkChroot,
s.FrameworkName,
)
if err != nil {
log.Errorf("Could not read reconciliation info from ZK: %#+v. "+
"Skipping task launch.", err)
return false
}
err = s.healthCheck(s.running)
if err != nil {
atomic.StoreUint32(&s.Stats.IsHealthy, 0)
atomic.AddUint32(&s.Stats.ClusterLivelocks, 1)
// If we have been unhealthy for reseedTimeout seconds, it's time to reseed.
if s.livelockWindow != nil {
if time.Since(*s.livelockWindow) > s.reseedTimeout {
log.Errorf("Cluster has been livelocked for longer than %d seconds!",
s.reseedTimeout/time.Second)
if s.autoReseedEnabled {
log.Warningf("Initiating reseed...")
// Set scheduler to immutable so that shouldLaunch bails out almost
// instantly, preventing multiple reseed events from occurring concurrently
go s.reseedCluster(driver)
} else {
log.Warning("Automatic reseed disabled (--auto-reseed=false). " +
"Doing nothing.")
}
return false
}
} else {
now := time.Now()
s.livelockWindow = &now
}
log.Errorf("Failed health check, rescheduling "+
"launch attempt for later: %s", err)
return false
}
atomic.StoreUint32(&s.Stats.IsHealthy, 1)
// reset livelock window because we're healthy
s.livelockWindow = nil
return true
}
// TODO(tyler) split this long function up!
func (s *EtcdScheduler) launchOne(driver scheduler.SchedulerDriver) {
// Always ensure we've pruned any dead / unmanaged nodes before
// launching new ones, or we may overconfigure the ensemble such
// that it can not make progress if the next launch fails.
err := s.Prune()
if err != nil {
log.Errorf("Failed to remove stale cluster members: %s", err)
return
}
if !s.shouldLaunch(driver) {
log.Infoln("Skipping launch attempt for now.")
return
}
// validOffer filters out offers that are no longer
// desirable, even though they may have been when
// they were enqueued.
validOffer := func(offer *mesos.Offer) bool {
runningCopy := s.RunningCopy()
for _, etcdConfig := range runningCopy {
if etcdConfig.SlaveID == offer.SlaveId.GetValue() {
if s.singleInstancePerSlave {
log.Info("Skipping offer: already running on this slave.")
return false
}
}
}
return true
}
// Issue BlockingPop until we get back an offer we can use.
var offer *mesos.Offer
for {
offer = s.offerCache.BlockingPop()
if validOffer(offer) {
break
} else {
s.decline(driver, offer)
}
}
// Do this again because BlockingPop may have taken a long time.
if !s.shouldLaunch(driver) {
log.Infoln("Skipping launch attempt for now.")
s.decline(driver, offer)
return
}
// TODO(tyler) this is a broken hack; task gets low ports, executor gets high ports
var (
resources = parseOffer(offer)
lowest = *resources.ports[0].Begin
rpcPort = lowest
clientPort = lowest + 1
httpPort = lowest + 2
libprocessPort = lowest + 3
)
s.mut.Lock()
var clusterType string
if len(s.running) == 0 {
clusterType = "new"
} else {
clusterType = "existing"
}
s.highestInstanceID++
name := "etcd-" + strconv.FormatInt(s.highestInstanceID, 10)
node := &config.Node{
Name: name,
Host: *offer.Hostname,
RPCPort: rpcPort,
ClientPort: clientPort,
ReseedPort: httpPort,
Type: clusterType,
SlaveID: offer.GetSlaveId().GetValue(),
}
running := []*config.Node{node}
for _, r := range s.running {
running = append(running, r)
}
serializedNodes, err := json.Marshal(running)
log.Infof("Serialized running: %+v", string(serializedNodes))
if err != nil {
log.Errorf("Could not serialize running list: %v", err)
// This Unlock is not deferred because the test implementation of LaunchTasks
// calls this scheduler's StatusUpdate method, causing the test to deadlock.
s.decline(driver, offer)
s.mut.Unlock()
return
}
configSummary := node.String()
taskID := &mesos.TaskID{Value: &configSummary}
executor := s.newExecutorInfo(node, s.executorUris, libprocessPort)
task := &mesos.TaskInfo{
Data: serializedNodes,
Name: proto.String("etcd-server"),
TaskId: taskID,
SlaveId: offer.SlaveId,
Executor: executor,
Resources: []*mesos.Resource{
util.NewScalarResource("cpus", s.cpusPerTask),
util.NewScalarResource("mem", s.memPerTask),
util.NewScalarResource("disk", s.diskPerTask),
util.NewRangesResource("ports", []*mesos.Value_Range{
util.NewValueRange(uint64(rpcPort), uint64(rpcPort+portsPerTask-1)),
}),
},
Discovery: &mesos.DiscoveryInfo{
Visibility: mesos.DiscoveryInfo_EXTERNAL.Enum(),
Name: proto.String("etcd-server"),
Ports: &mesos.Ports{
Ports: []*mesos.Port{
{
Number: proto.Uint32(uint32(rpcPort)),
Protocol: proto.String("tcp"),
},
// HACK: "client" is not a real SRV protocol. This is so
// that we can have etcd proxies use srv discovery on the
// above tcp name. Mesos-dns does not yet care about
// names for DiscoveryInfo. When it does, we should
// create a name for clients to use. We want to keep
// the rpcPort accessible at _etcd-server._tcp.<fwname>.mesos
{
Number: proto.Uint32(uint32(clientPort)),
Protocol: proto.String("client"),
},
},
},
},
}
log.Infof(
"Prepared task: %s with offer %s for launch",
task.GetName(),
offer.Id.GetValue(),
)
log.Info("Launching etcd node.")
tasks := []*mesos.TaskInfo{task}
s.pending[node.Name] = struct{}{}
// This Unlock is not deferred because the test implementation of LaunchTasks
// calls this scheduler's StatusUpdate method, causing the test to deadlock.
s.mut.Unlock()
atomic.AddUint32(&s.Stats.LaunchedServers, 1)
driver.LaunchTasks(