/
main.go
858 lines (739 loc) · 22.9 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
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
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Licensed 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 main
import (
"net/url"
"os"
"strings"
"time"
"github.com/uber/peloton/.gen/peloton/private/resmgrsvc"
cqos "github.com/uber/peloton/.gen/qos/v1alpha1"
"github.com/uber/peloton/pkg/auth"
auth_impl "github.com/uber/peloton/pkg/auth/impl"
"github.com/uber/peloton/pkg/common"
"github.com/uber/peloton/pkg/common/background"
"github.com/uber/peloton/pkg/common/backoff"
"github.com/uber/peloton/pkg/common/buildversion"
"github.com/uber/peloton/pkg/common/config"
"github.com/uber/peloton/pkg/common/health"
"github.com/uber/peloton/pkg/common/leader"
"github.com/uber/peloton/pkg/common/logging"
"github.com/uber/peloton/pkg/common/metrics"
"github.com/uber/peloton/pkg/common/rpc"
"github.com/uber/peloton/pkg/hostmgr"
bin_packing "github.com/uber/peloton/pkg/hostmgr/binpacking"
"github.com/uber/peloton/pkg/hostmgr/goalstate"
"github.com/uber/peloton/pkg/hostmgr/host"
"github.com/uber/peloton/pkg/hostmgr/host/drainer"
"github.com/uber/peloton/pkg/hostmgr/hostpool/hostmover"
"github.com/uber/peloton/pkg/hostmgr/hostpool/manager"
"github.com/uber/peloton/pkg/hostmgr/hostsvc"
"github.com/uber/peloton/pkg/hostmgr/mesos"
"github.com/uber/peloton/pkg/hostmgr/mesos/yarpc/encoding/mpb"
"github.com/uber/peloton/pkg/hostmgr/mesos/yarpc/peer"
"github.com/uber/peloton/pkg/hostmgr/mesos/yarpc/transport/mhttp"
hostmetric "github.com/uber/peloton/pkg/hostmgr/metrics"
"github.com/uber/peloton/pkg/hostmgr/offer"
"github.com/uber/peloton/pkg/hostmgr/p2k/hostcache"
"github.com/uber/peloton/pkg/hostmgr/p2k/hostmgrsvc"
"github.com/uber/peloton/pkg/hostmgr/p2k/plugins"
mesosplugins "github.com/uber/peloton/pkg/hostmgr/p2k/plugins/mesos"
"github.com/uber/peloton/pkg/hostmgr/p2k/podeventmanager"
"github.com/uber/peloton/pkg/hostmgr/p2k/scalar"
"github.com/uber/peloton/pkg/hostmgr/queue"
"github.com/uber/peloton/pkg/hostmgr/reconcile"
"github.com/uber/peloton/pkg/hostmgr/watchevent"
"github.com/uber/peloton/pkg/middleware/inbound"
"github.com/uber/peloton/pkg/middleware/outbound"
"github.com/uber/peloton/pkg/storage/cassandra"
ormobjects "github.com/uber/peloton/pkg/storage/objects"
"github.com/uber/peloton/pkg/storage/stores"
log "github.com/sirupsen/logrus"
_ "go.uber.org/automaxprocs"
"go.uber.org/yarpc"
"go.uber.org/yarpc/api/transport"
"go.uber.org/yarpc/transport/grpc"
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
var (
version string
app = kingpin.New("peloton-hostmgr", "Peloton Host Manager")
debug = app.Flag(
"debug", "enable debug mode (print full json responses)").
Short('d').
Default("false").
Envar("ENABLE_DEBUG_LOGGING").
Bool()
enableSentry = app.Flag(
"enable-sentry", "enable logging hook up to sentry").
Default("false").
Envar("ENABLE_SENTRY_LOGGING").
Bool()
configFiles = app.Flag(
"config",
"YAML config files (can be provided multiple times to merge configs)").
Short('c').
Required().
ExistingFiles()
dbHost = app.Flag(
"db-host",
"Database host (db.host override) (set $DB_HOST to override)").
Envar("DB_HOST").
String()
electionZkServers = app.Flag(
"election-zk-server",
"Election Zookeeper servers. Specify multiple times for multiple servers "+
"(election.zk_servers override) (set $ELECTION_ZK_SERVERS to override)").
Envar("ELECTION_ZK_SERVERS").
Strings()
httpPort = app.Flag(
"http-port", "Host manager HTTP port (hostmgr.http_port override) "+
"(set $HTTP_PORT to override)").
Envar("HTTP_PORT").
Int()
grpcPort = app.Flag(
"grpc-port", "Host manager GRPC port (hostmgr.grpc_port override) "+
"(set $GRPC_PORT to override)").
Envar("GRPC_PORT").
Int()
zkPath = app.Flag(
"zk-path",
"Zookeeper path (mesos.zk_host override) (set $MESOS_ZK_PATH to override)").
Envar("MESOS_ZK_PATH").
String()
useCassandra = app.Flag(
"use-cassandra", "Use cassandra storage implementation").
Default("true").
Envar("USE_CASSANDRA").
Bool()
cassandraHosts = app.Flag(
"cassandra-hosts", "Cassandra hosts").
Envar("CASSANDRA_HOSTS").
Strings()
cassandraStore = app.Flag(
"cassandra-store", "Cassandra store name").
Default("").
Envar("CASSANDRA_STORE").
String()
cassandraPort = app.Flag(
"cassandra-port", "Cassandra port to connect").
Default("0").
Envar("CASSANDRA_PORT").
Int()
autoMigrate = app.Flag(
"auto-migrate", "Automatically update storage schemas.").
Default("false").
Envar("AUTO_MIGRATE").
Bool()
datacenter = app.Flag(
"datacenter", "Datacenter name").
Default("").
Envar("DATACENTER").
String()
mesosSecretFile = app.Flag(
"mesos-secret-file",
"Secret file containing one-liner password to connect to Mesos master").
Default("").
Envar("MESOS_SECRET_FILE").
String()
pelotonSecretFile = app.Flag(
"peloton-secret-file",
"Secret file containing all Peloton secrets").
Default("").
Envar("PELOTON_SECRET_FILE").
String()
scarceResourceTypes = app.Flag(
"scarce-resource-type", "Scarce Resource Type.").
Envar("SCARCE_RESOURCE_TYPES").
String()
slackResourceTypes = app.Flag(
"slack-resource-type", "Slack Resource Type.").
Envar("SLACK_RESOURCE_TYPES").
String()
enableRevocableResources = app.Flag(
"enable-revocable-resources", "Revcocable Resources Enabled").
Envar("ENABLE_REVOCABLE_RESOURCES").
Bool()
binPacking = app.Flag(
"bin_packing", "Bin Packing enable/disable, by default disabled.").
Envar("BIN_PACKING").
String()
qoSAdvisorServiceAddress = app.Flag(
"qos_advisor_service_address", "Qos advisor service address.").
Default("").
Envar("QOS_ADVISOR_SERVICE_ADDRESS").
String()
authType = app.Flag(
"auth-type",
"Define the auth type used, default to NOOP").
Default("NOOP").
Envar("AUTH_TYPE").
Enum("NOOP", "BASIC")
authConfigFile = app.Flag(
"auth-config-file",
"config file for the auth feature, which is specific to the auth type used").
Default("").
Envar("AUTH_CONFIG_FILE").
String()
kubeConfigFile = app.Flag(
"kube-config-file",
"YAML config file for kubernetes plugin").
Default("").
Envar("KUBECONFIG").
String()
enableK8s = app.Flag(
"enable-k8s",
"Enable k8s plugin").
Envar("ENABLE_K8S").
Bool()
enableHostPool = app.Flag(
"enable-host-pool",
"Enable Host Pool Management").
Envar("ENABLE_HOST_POOL").
Bool()
)
const (
taskEvictionQueueName = "task-eviction-queue"
)
func main() {
app.Version(version)
app.HelpFlag.Short('h')
kingpin.MustParse(app.Parse(os.Args[1:]))
log.SetFormatter(
&logging.LogFieldFormatter{
Formatter: &logging.SecretsFormatter{Formatter: &log.JSONFormatter{}},
Fields: log.Fields{
common.AppLogField: app.Name,
},
},
)
initialLevel := log.InfoLevel
if *debug {
initialLevel = log.DebugLevel
}
log.SetLevel(initialLevel)
log.WithField("files", *configFiles).Info("Loading host manager config")
var cfg Config
if err := config.Parse(&cfg, *configFiles...); err != nil {
log.WithField("error", err).Fatal("Cannot parse yaml config")
}
if *enableSentry {
logging.ConfigureSentry(&cfg.SentryConfig)
}
// now, override any CLI flags in the loaded config.Config
if *httpPort != 0 {
cfg.HostManager.HTTPPort = *httpPort
}
if *grpcPort != 0 {
cfg.HostManager.GRPCPort = *grpcPort
}
if *zkPath != "" {
cfg.Mesos.ZkPath = *zkPath
}
if len(*electionZkServers) > 0 {
cfg.Election.ZKServers = *electionZkServers
}
if !*useCassandra {
cfg.Storage.UseCassandra = false
}
if *cassandraHosts != nil && len(*cassandraHosts) > 0 {
cfg.Storage.Cassandra.CassandraConn.ContactPoints = *cassandraHosts
}
// Parse and setup peloton auth
if len(*authType) != 0 {
cfg.Auth.AuthType = auth.Type(*authType)
cfg.Auth.Path = *authConfigFile
}
// Parse and setup peloton secrets
if *pelotonSecretFile != "" {
var secretsCfg config.PelotonSecretsConfig
if err := config.Parse(&secretsCfg, *pelotonSecretFile); err != nil {
log.WithError(err).
WithField("peloton_secret_file", *pelotonSecretFile).
Fatal("Cannot parse secret config")
}
cfg.Storage.Cassandra.CassandraConn.Username =
secretsCfg.CassandraUsername
cfg.Storage.Cassandra.CassandraConn.Password =
secretsCfg.CassandraPassword
}
if *cassandraStore != "" {
cfg.Storage.Cassandra.StoreName = *cassandraStore
}
if *cassandraPort != 0 {
cfg.Storage.Cassandra.CassandraConn.Port = *cassandraPort
}
if *autoMigrate {
cfg.Storage.AutoMigrate = *autoMigrate
}
if *datacenter != "" {
cfg.Storage.Cassandra.CassandraConn.DataCenter = *datacenter
}
if *scarceResourceTypes != "" {
log.Info(strings.Split(*scarceResourceTypes, ","))
cfg.HostManager.ScarceResourceTypes = strings.Split(*scarceResourceTypes, ",")
}
if *slackResourceTypes != "" {
log.Info(strings.Split(*slackResourceTypes, ","))
cfg.HostManager.SlackResourceTypes = strings.Split(*slackResourceTypes, ",")
}
if *enableRevocableResources {
log.Info("Revocable Resource Enabled")
cfg.Mesos.Framework.RevocableResourcesSupported = *enableRevocableResources
}
if *binPacking != "" {
log.Info("Bin Packing is enabled")
cfg.HostManager.BinPacking = *binPacking
}
if *enableK8s {
cfg.K8s.Enabled = true
}
if *kubeConfigFile != "" {
cfg.K8s.Kubeconfig = *kubeConfigFile
}
if *qoSAdvisorServiceAddress != "" {
cfg.HostManager.QoSAdvisorService.Address = *qoSAdvisorServiceAddress
}
if *enableHostPool {
log.Info("Host Pool Management Enabled")
cfg.HostManager.EnableHostPool = *enableHostPool
}
log.WithField("config", cfg).Info("Loaded Host Manager configuration")
rootScope, scopeCloser, mux := metrics.InitMetricScope(
&cfg.Metrics,
common.PelotonHostManager,
metrics.TallyFlushInterval,
)
defer scopeCloser.Close()
mux.HandleFunc(
logging.LevelOverwrite,
logging.LevelOverwriteHandler(initialLevel))
mux.HandleFunc(buildversion.Get, buildversion.Handler(version))
// Create both HTTP and GRPC inbounds
inbounds := rpc.NewInbounds(
cfg.HostManager.HTTPPort,
cfg.HostManager.GRPCPort,
mux,
)
// TODO: Skip it when k8s is enabled.
mesosMasterDetector, err := mesos.NewZKDetector(cfg.Mesos.ZkPath)
if err != nil {
log.Fatalf("Failed to initialize mesos master detector: %v", err)
}
// NOTE: we start the server immediately even if no leader has been
// detected yet.
rootScope.Counter("boot").Inc(1)
store := stores.MustCreateStore(&cfg.Storage, rootScope)
ormStore, ormErr := ormobjects.NewCassandraStore(
cassandra.ToOrmConfig(&cfg.Storage.Cassandra),
rootScope)
if ormErr != nil {
log.WithError(ormErr).Fatal("Failed to create ORM store for Cassandra")
}
activeJobsOps := ormobjects.NewActiveJobsOps(ormStore)
authHeader, err := mesos.GetAuthHeader(&cfg.Mesos, *mesosSecretFile)
if err != nil {
log.WithError(err).Fatal("Cannot initialize auth header")
}
// Initialize YARPC dispatcher with necessary inbounds and outbounds
driver := mesos.InitSchedulerDriver(
&cfg.Mesos,
store, // store implements FrameworkInfoStore
authHeader,
)
// Active host manager needs a Mesos inbound
var mInbound = mhttp.NewInbound(rootScope, driver)
inbounds = append(inbounds, mInbound)
// TODO: update Mesos url when leading mesos master changes
mOutbound := mhttp.NewOutbound(
rootScope,
mesosMasterDetector,
driver.Endpoint(),
authHeader,
mhttp.MaxConnectionsPerHost(cfg.Mesos.Framework.MaxConnectionsToMesosMaster),
)
// MasterOperatorClient API outbound
mOperatorOutbound := mhttp.NewOutbound(
rootScope,
mesosMasterDetector,
url.URL{
Scheme: "http",
Path: common.MesosMasterOperatorEndPoint,
},
authHeader,
mhttp.MaxConnectionsPerHost(cfg.Mesos.Framework.MaxConnectionsToMesosMaster),
)
// All leader discovery metrics share a scope (and will be tagged
// with role={role})
discoveryScope := rootScope.SubScope("discovery")
// TODO: Delete the outbounds from hostmgr to resmgr after switch
// eventstream from push to pull (T1014913)
// Setup the discovery service to detect resmgr leaders and
// configure the YARPC Peer dynamically
t := rpc.NewTransport()
resmgrPeerChooser, err := peer.NewSmartChooser(
cfg.Election,
discoveryScope,
common.ResourceManagerRole,
t,
)
if err != nil {
log.WithFields(log.Fields{"error": err, "role": common.ResourceManagerRole}).
Fatal("Could not create smart peer chooser")
}
defer resmgrPeerChooser.Stop()
resmgrOutbound := t.NewOutbound(resmgrPeerChooser)
outbounds := yarpc.Outbounds{
common.MesosMasterScheduler: mOutbound,
common.MesosMasterOperator: mOperatorOutbound,
common.PelotonResourceManager: transport.Outbounds{
Unary: resmgrOutbound,
},
}
if cfg.HostManager.QoSAdvisorService.Address != "" {
var cqosOutbound *grpc.Outbound
// Setup the discovery service to detect QoSAdvisorService
cqosTransport := grpc.NewTransport()
cqosOutbound = cqosTransport.NewSingleOutbound(cfg.HostManager.
QoSAdvisorService.Address)
outbounds[common.QoSAdvisorService] =
transport.Outbounds{
Unary: cqosOutbound,
}
}
securityManager, err := auth_impl.CreateNewSecurityManager(&cfg.Auth)
if err != nil {
log.WithError(err).
Fatal("Could not enable security feature")
}
authInboundMiddleware := inbound.NewAuthInboundMiddleware(securityManager)
securityClient, err := auth_impl.CreateNewSecurityClient(&cfg.Auth)
if err != nil {
log.WithError(err).
Fatal("Could not establish secure inter-component communication")
}
authOutboundMiddleware := outbound.NewAuthOutboundMiddleware(securityClient)
leaderCheckMiddleware := &inbound.LeaderCheckInboundMiddleware{}
dispatcher := yarpc.NewDispatcher(yarpc.Config{
Name: common.PelotonHostManager,
Inbounds: inbounds,
Outbounds: outbounds,
Metrics: yarpc.MetricsConfig{
Tally: rootScope,
},
InboundMiddleware: yarpc.InboundMiddleware{
Unary: yarpc.UnaryInboundMiddleware(authInboundMiddleware, leaderCheckMiddleware),
Oneway: yarpc.OnewayInboundMiddleware(authInboundMiddleware, leaderCheckMiddleware),
Stream: yarpc.StreamInboundMiddleware(authInboundMiddleware, leaderCheckMiddleware),
},
OutboundMiddleware: yarpc.OutboundMiddleware{
Unary: authOutboundMiddleware,
Oneway: authOutboundMiddleware,
Stream: authOutboundMiddleware,
},
})
// Init the managers driven by the mesos callbacks.
// They are driven by the leader who will subscribe to
// Mesos callbacks
// NOTE: This blocks us to move all Mesos related logic into
// hostmgr.Server because schedulerClient uses dispatcher...
schedulerClient := mpb.NewSchedulerClient(
dispatcher.ClientConfig(common.MesosMasterScheduler),
cfg.Mesos.Encoding,
)
masterOperatorClient := mpb.NewMasterOperatorClient(
dispatcher.ClientConfig(common.MesosMasterOperator),
cfg.Mesos.Encoding,
)
mesos.InitManager(
dispatcher,
&cfg.Mesos,
store, // store implements FrameworkInfoStore
)
var cQosClient cqos.QoSAdvisorServiceYARPCClient
if cfg.HostManager.QoSAdvisorService.Address != "" {
cQosClient = cqos.NewQoSAdvisorServiceYARPCClient(
dispatcher.ClientConfig(common.QoSAdvisorService))
}
log.WithFields(log.Fields{
"http_port": cfg.HostManager.HTTPPort,
"url_path": common.PelotonEndpointPath,
}).Info("HostService initialized")
// Declare background works
reconciler := reconcile.NewTaskReconciler(
schedulerClient,
rootScope,
driver,
activeJobsOps,
store, // store implements TaskStore
cfg.HostManager.TaskReconcilerConfig,
)
ormobjects.InitHostInfoOps(ormStore)
loader := host.Loader{
OperatorClient: masterOperatorClient,
Scope: rootScope.SubScope("hostmap"),
SlackResourceTypes: cfg.HostManager.SlackResourceTypes,
HostInfoOps: ormobjects.GetHostInfoOps(),
}
backgroundManager := background.NewManager()
// Retry on hostmap loader with Background Manager.
err = backoff.Retry(
func() error {
return backgroundManager.RegisterWorks(
background.Work{
Name: "hostmap",
Func: loader.Load,
Period: cfg.HostManager.HostmapRefreshInterval,
},
)
}, backoff.NewRetryPolicy(cfg.HostManager.HostMgrBackoffRetryCount,
time.Duration(cfg.HostManager.HostMgrBackoffRetryIntervalSec)*time.Second),
func(error) bool {
return true
})
if err != nil {
log.WithError(err).Fatal("Cannot register hostmap loader background worker.")
}
// Retry on reconciler registry with Background Manager.
err = backoff.Retry(
func() error {
return backgroundManager.RegisterWorks(
background.Work{
Name: "reconciler",
Func: reconciler.Reconcile,
Period: time.Duration(
cfg.HostManager.TaskReconcilerConfig.ReconcileIntervalSec) * time.Second,
InitialDelay: time.Duration(
cfg.HostManager.TaskReconcilerConfig.InitialReconcileDelaySec) * time.Second,
},
)
}, backoff.NewRetryPolicy(cfg.HostManager.HostMgrBackoffRetryCount,
time.Duration(cfg.HostManager.HostMgrBackoffRetryIntervalSec)*time.Second),
func(error) bool {
return true
})
if err != nil {
log.WithError(err).Fatal("Cannot register reconciler background worker.")
}
metric := hostmetric.NewMetrics(rootScope)
if cfg.HostManager.QoSAdvisorService.Address != "" {
bin_packing.Init(cQosClient, metric)
} else {
bin_packing.Init(nil, nil)
}
log.WithField("ranker_name", cfg.HostManager.BinPacking).
Info("Bin packing is enabled")
defaultRanker := bin_packing.GetRankerByName(cfg.HostManager.BinPacking)
if defaultRanker == nil {
log.WithField("ranker_name", cfg.HostManager.BinPacking).
Fatal("Ranker not found")
}
watchevent.InitWatchProcessor(cfg.HostManager.Watch, metric)
watchProcessor := watchevent.GetWatchProcessor()
plugin := plugins.NewNoopPlugin()
var hostCache hostcache.HostCache
podEventCh := make(chan *scalar.PodEvent, plugins.EventChanSize)
hostEventCh := make(chan *scalar.HostEvent, plugins.EventChanSize)
// If k8s is enabled, return a k8s plugin.
// TODO: start MesosPlugin after it's implemented.
if cfg.K8s.Enabled {
var err error
plugin, err = plugins.NewK8sPlugin(
cfg.K8s.Kubeconfig,
podEventCh,
hostEventCh,
)
if err != nil {
log.WithError(err).Fatal("Cannot init host manager plugin.")
}
}
// a temporary measure to enable mesos plugins for some usecases,
// it is not fully ready to be used for v1alpha handler.
mesosPlugin := mesosplugins.NewMesosManager(
dispatcher,
driver,
schedulerClient,
masterOperatorClient,
cfg.HostManager.HostmapRefreshInterval,
time.Duration(cfg.HostManager.OfferHoldTimeSec)*time.Second,
rootScope,
podEventCh,
hostEventCh,
)
// Initialize offer pool event handler with nil host pool manager.
// TODO: Refactor event stream handler and move it out of offer package
// to avoid circular dependency, since now offer pool event handler requires
// host pool manager, and host pool manager requires event stream handler
// which is part of offer pool event handler.
offer.InitEventHandler(
dispatcher,
rootScope,
schedulerClient,
resmgrsvc.NewResourceManagerServiceYARPCClient(
dispatcher.ClientConfig(common.PelotonResourceManager)),
backgroundManager,
defaultRanker,
cfg.HostManager,
watchProcessor,
nil,
mesosPlugin,
)
// Construct host pool manager if it is enabled.
var hostPoolManager manager.HostPoolManager
if cfg.HostManager.EnableHostPool {
hostPoolManager = manager.New(
cfg.HostManager.HostPoolReconcileInterval,
offer.GetEventHandler().GetEventStreamHandler(),
ormobjects.GetHostInfoOps(),
rootScope,
)
// Set host pool manager in offer pool event handler.
offer.GetEventHandler().SetHostPoolManager(hostPoolManager)
}
// Create host cache instance.
hostCache = hostcache.New(
hostEventCh,
backgroundManager,
rootScope,
)
pem := podeventmanager.New(
dispatcher,
podEventCh,
plugin,
hostCache,
cfg.HostManager.TaskUpdateBufferSize,
rootScope,
cfg.K8s.Enabled)
// Create v1alpha hostmgr internal service handler.
hostmgrsvc.NewServiceHandler(
dispatcher,
rootScope,
plugin,
hostCache,
pem,
)
// Create Goal State Engine driver
goalStateDriver := goalstate.NewDriver(
ormobjects.GetHostInfoOps(),
masterOperatorClient,
rootScope,
cfg.HostManager.GoalState,
hostPoolManager,
)
// Create Host mover object
hostMover := hostmover.NewHostMover(
hostPoolManager,
ormobjects.GetHostInfoOps(),
goalStateDriver,
rootScope,
resmgrsvc.NewResourceManagerServiceYARPCClient(
dispatcher.ClientConfig(common.PelotonResourceManager)),
)
taskEvictionQueue := queue.NewTaskQueue(taskEvictionQueueName)
// Create new hostmgr internal service handler.
serviceHandler := hostmgr.NewServiceHandler(
dispatcher,
metric,
schedulerClient,
masterOperatorClient,
driver,
cfg.Mesos,
mesosMasterDetector,
&cfg.HostManager,
cfg.HostManager.SlackResourceTypes,
watchProcessor,
hostPoolManager,
goalStateDriver,
ormobjects.GetHostInfoOps(),
hostCache,
mesosPlugin,
)
hostDrainer := drainer.NewDrainer(
cfg.HostManager.HostDrainerPeriod,
cfg.Mesos.Framework.Role,
masterOperatorClient,
goalStateDriver,
ormobjects.GetHostInfoOps(),
taskEvictionQueue,
)
hostsvc.InitServiceHandler(
dispatcher,
rootScope,
hostDrainer,
hostPoolManager,
hostMover,
)
recoveryHandler := hostmgr.NewRecoveryHandler(
rootScope,
store,
ormStore,
hostCache,
)
server := hostmgr.NewServer(
rootScope,
backgroundManager,
cfg.HostManager.HTTPPort,
cfg.HostManager.GRPCPort,
mesosMasterDetector,
mInbound,
mOutbound,
reconciler,
recoveryHandler,
hostDrainer,
serviceHandler.GetReserver(),
watchProcessor,
plugin,
hostCache,
mesosPlugin,
hostPoolManager,
)
server.Start()
// Start dispatch loop.
if err := dispatcher.Start(); err != nil {
log.Fatalf("Could not start rpc server: %v", err)
}
// Set nomination for leader check middleware
leaderCheckMiddleware.SetNomination(server)
candidate, err := leader.NewCandidate(
cfg.Election,
rootScope,
common.HostManagerRole,
server,
)
if err != nil {
log.Fatalf("Unable to create leader candidate: %v", err)
}
err = candidate.Start()
if err != nil {
log.Fatalf("Unable to start leader candidate: %v", err)
}
defer candidate.Stop()
// Start dispatch loop.
if err := dispatcher.Start(); err != nil {
log.Fatalf("Could not start rpc server: %v", err)
}
defer dispatcher.Stop()
log.WithFields(log.Fields{
"httpPort": cfg.HostManager.HTTPPort,
"grpcPort": cfg.HostManager.GRPCPort,
}).Info("Started host manager")
// We can *honestly* say the server is booted up now.
health.InitHeartbeat(rootScope, cfg.Health, candidate)
// Start collecting runtime metrics.
defer metrics.StartCollectingRuntimeMetrics(
rootScope,
cfg.Metrics.RuntimeMetrics.Enabled,
cfg.Metrics.RuntimeMetrics.CollectInterval)()
select {}
}