forked from mesos/mesos-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
459 lines (406 loc) · 16.2 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
/**
* 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 main
import (
"flag"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strconv"
"strings"
"github.com/gogo/protobuf/proto"
log "github.com/golang/glog"
"github.com/mesos/mesos-go/api/v0/auth"
"github.com/mesos/mesos-go/api/v0/auth/sasl"
"github.com/mesos/mesos-go/api/v0/auth/sasl/mech"
mesos "github.com/mesos/mesos-go/api/v0/mesosproto"
util "github.com/mesos/mesos-go/api/v0/mesosutil"
sched "github.com/mesos/mesos-go/api/v0/scheduler"
"golang.org/x/net/context"
)
const (
CPUS_PER_TASK = 1
MEM_PER_TASK = 128
DISK_PER_TASK = 20
defaultArtifactPort = 12345
)
var (
address = flag.String("address", "127.0.0.1", "Binding address for artifact server")
artifactPort = flag.Int("artifactPort", defaultArtifactPort, "Binding port for artifact server")
authProvider = flag.String("mesos_authentication_provider", sasl.ProviderName,
fmt.Sprintf("Authentication provider to use, default is SASL that supports mechanisms: %+v", mech.ListSupported()))
master = flag.String("master", "127.0.0.1:5050", "Master address <ip:port>")
executorPath = flag.String("executor", "./executor", "Path to test executor")
taskCount = flag.String("task-count", "5", "Total task count to run.")
role = flag.String("role", "golang", "Role for framework and tasks.")
mesosAuthPrincipal = flag.String("mesos_authentication_principal", "", "Mesos authentication principal.")
mesosAuthSecretFile = flag.String("mesos_authentication_secret_file", "", "Mesos authentication secret file.")
execUri *string
execCmd string
)
type ExampleScheduler struct {
tasks []*ExampleTask
}
type ExampleTaskState int
const (
InitState ExampleTaskState = iota
RequestedReservationState
LaunchedState
FinishedState
UnreservedState
)
type ExampleTask struct {
executor *mesos.ExecutorInfo
name string
persistenceId string
containerPath string
state ExampleTaskState
}
func newExampleScheduler() *ExampleScheduler {
total, err := strconv.Atoi(*taskCount)
if err != nil {
total = 5
}
tasks := make([]*ExampleTask, total)
for i := 0; i < total; i++ {
tasks[i] = &ExampleTask{
executor: prepareExecutorInfo(fmt.Sprintf("persistent-task-executor-%d", i+1)),
name: fmt.Sprintf("persistent-task-%d", i+1),
persistenceId: fmt.Sprintf("persistence-%d", i+1),
containerPath: "data",
state: InitState,
}
}
return &ExampleScheduler{
tasks: tasks,
}
}
func getResource(name string, resources []*mesos.Resource, withReservation bool) float64 {
filtered := util.FilterResources(resources, func(res *mesos.Resource) bool {
if withReservation {
return res.GetName() == name && res.Reservation != nil
}
return res.GetName() == name && res.Reservation == nil
})
val := 0.0
for _, res := range filtered {
val += res.GetScalar().GetValue()
}
return val
}
func resourcesHaveVolume(resources []*mesos.Resource, persistenceId string) bool {
filtered := util.FilterResources(resources, func(res *mesos.Resource) bool {
return res.GetName() == "disk" &&
res.Reservation != nil &&
res.Disk != nil &&
res.Disk.Persistence.GetId() == persistenceId
})
return len(filtered) > 0
}
func getUnreservedResources(resources []*mesos.Resource) (float64, float64, float64) {
return getResource("cpus", resources, false), getResource("mem", resources, false), getResource("disk", resources, false)
}
func getReservedResources(resources []*mesos.Resource) (float64, float64, float64) {
return getResource("cpus", resources, true), getResource("mem", resources, true), getResource("disk", resources, true)
}
func (sched *ExampleScheduler) Registered(driver sched.SchedulerDriver, frameworkId *mesos.FrameworkID, masterInfo *mesos.MasterInfo) {
log.Infoln("Framework Registered with Master ", masterInfo)
}
func (sched *ExampleScheduler) Reregistered(driver sched.SchedulerDriver, masterInfo *mesos.MasterInfo) {
log.Infoln("Framework Re-Registered with Master ", masterInfo)
}
func (sched *ExampleScheduler) Disconnected(sched.SchedulerDriver) {
log.Fatalf("disconnected from master, aborting")
}
func (sched *ExampleScheduler) ResourceOffers(driver sched.SchedulerDriver, offers []*mesos.Offer) {
for _, offer := range offers {
operations := []*mesos.Offer_Operation{}
resourcesToCreate := []*mesos.Resource{}
resourcesToDestroy := []*mesos.Resource{}
resourcesToReserve := []*mesos.Resource{}
resourcesToUnreserve := []*mesos.Resource{}
taskInfosToLaunch := []*mesos.TaskInfo{}
totalUnreserved := 0
unreservedCpus, unreservedMem, unreservedDisk := getUnreservedResources(offer.Resources)
reservedCpus, reservedMem, reservedDisk := getReservedResources(offer.Resources)
log.Infoln("Received Offer <", offer.Id.GetValue(), "> with unreserved cpus=", unreservedCpus, " mem=", unreservedMem, " disk=", unreservedDisk)
log.Infoln("Received Offer <", offer.Id.GetValue(), "> with reserved cpus=", reservedCpus, " mem=", reservedMem, " disk=", reservedDisk)
for _, task := range sched.tasks {
switch task.state {
case InitState:
if CPUS_PER_TASK <= unreservedCpus &&
MEM_PER_TASK <= unreservedMem &&
DISK_PER_TASK <= unreservedDisk {
resourcesToReserve = append(resourcesToReserve, []*mesos.Resource{
util.NewScalarResourceWithReservation("cpus", CPUS_PER_TASK, *mesosAuthPrincipal, *role),
util.NewScalarResourceWithReservation("mem", MEM_PER_TASK, *mesosAuthPrincipal, *role),
util.NewScalarResourceWithReservation("disk", DISK_PER_TASK, *mesosAuthPrincipal, *role),
}...)
resourcesToCreate = append(resourcesToCreate,
util.NewVolumeResourceWithReservation(DISK_PER_TASK, task.containerPath, task.persistenceId, mesos.Volume_RW.Enum(), *mesosAuthPrincipal, *role))
task.state = RequestedReservationState
unreservedCpus = unreservedCpus - CPUS_PER_TASK
unreservedMem = unreservedMem - MEM_PER_TASK
unreservedDisk = unreservedDisk - DISK_PER_TASK
}
case RequestedReservationState:
if CPUS_PER_TASK <= reservedCpus &&
MEM_PER_TASK <= reservedMem &&
DISK_PER_TASK <= reservedDisk &&
resourcesHaveVolume(offer.Resources, task.persistenceId) {
taskId := &mesos.TaskID{
Value: proto.String(task.name),
}
taskInfo := &mesos.TaskInfo{
Name: proto.String("go-task-" + taskId.GetValue()),
TaskId: taskId,
SlaveId: offer.SlaveId,
Executor: task.executor,
Resources: []*mesos.Resource{
util.NewScalarResourceWithReservation("cpus", CPUS_PER_TASK, *mesosAuthPrincipal, *role),
util.NewScalarResourceWithReservation("mem", MEM_PER_TASK, *mesosAuthPrincipal, *role),
util.NewVolumeResourceWithReservation(DISK_PER_TASK, task.containerPath, task.persistenceId, mesos.Volume_RW.Enum(), *mesosAuthPrincipal, *role),
},
}
taskInfosToLaunch = append(taskInfosToLaunch, taskInfo)
task.state = LaunchedState
reservedCpus = reservedCpus - CPUS_PER_TASK
reservedMem = reservedMem - MEM_PER_TASK
reservedDisk = reservedDisk - DISK_PER_TASK
log.Infof("Prepared task: %s with offer %s for launch\n", taskInfo.GetName(), offer.Id.GetValue())
}
case FinishedState:
resourcesToDestroy = append(resourcesToDestroy,
util.NewVolumeResourceWithReservation(DISK_PER_TASK, task.containerPath, task.persistenceId, mesos.Volume_RW.Enum(), *mesosAuthPrincipal, *role))
resourcesToUnreserve = append(resourcesToUnreserve, []*mesos.Resource{
util.NewScalarResourceWithReservation("cpus", CPUS_PER_TASK, *mesosAuthPrincipal, *role),
util.NewScalarResourceWithReservation("mem", MEM_PER_TASK, *mesosAuthPrincipal, *role),
util.NewScalarResourceWithReservation("disk", DISK_PER_TASK, *mesosAuthPrincipal, *role),
}...)
task.state = UnreservedState
case UnreservedState:
totalUnreserved = totalUnreserved + 1
}
}
// Clean up reservations we no longer need
if len(resourcesToReserve) == 0 && len(resourcesToCreate) == 0 && len(taskInfosToLaunch) == 0 {
if reservedCpus >= 0.0 {
resourcesToUnreserve = append(resourcesToUnreserve, util.NewScalarResourceWithReservation("cpus", reservedCpus, *mesosAuthPrincipal, *role))
}
if reservedMem >= 0.0 {
resourcesToUnreserve = append(resourcesToUnreserve, util.NewScalarResourceWithReservation("mem", reservedCpus, *mesosAuthPrincipal, *role))
}
if reservedDisk >= 0.0 {
filtered := util.FilterResources(offer.Resources, func(res *mesos.Resource) bool {
return res.GetName() == "disk" &&
res.Reservation != nil &&
res.Disk != nil
})
for _, volume := range filtered {
resourcesToDestroy = append(resourcesToDestroy,
util.NewVolumeResourceWithReservation(
volume.GetScalar().GetValue(),
volume.Disk.Volume.GetContainerPath(),
volume.Disk.Persistence.GetId(),
volume.Disk.Volume.Mode,
*mesosAuthPrincipal,
*role))
}
resourcesToUnreserve = append(resourcesToUnreserve, util.NewScalarResourceWithReservation("mem", reservedDisk, *mesosAuthPrincipal, *role))
}
}
// Make a single operation per type
if len(resourcesToReserve) > 0 {
operations = append(operations, util.NewReserveOperation(resourcesToReserve))
}
if len(resourcesToCreate) > 0 {
operations = append(operations, util.NewCreateOperation(resourcesToCreate))
}
if len(resourcesToUnreserve) > 0 {
operations = append(operations, util.NewUnreserveOperation(resourcesToUnreserve))
}
if len(resourcesToDestroy) > 0 {
operations = append(operations, util.NewDestroyOperation(resourcesToDestroy))
}
if len(taskInfosToLaunch) > 0 {
operations = append(operations, util.NewLaunchOperation(taskInfosToLaunch))
}
log.Infoln("Accepting offers with ", len(operations), "operations for offer", offer.Id.GetValue())
refuseSeconds := 5.0
if len(operations) == 0 {
refuseSeconds = 5.0
}
driver.AcceptOffers([]*mesos.OfferID{offer.Id}, operations, &mesos.Filters{RefuseSeconds: proto.Float64(refuseSeconds)})
if totalUnreserved >= len(sched.tasks) {
log.Infoln("Total tasks completed and unreserved, stopping framework.")
driver.Stop(false)
}
}
}
func (sched *ExampleScheduler) StatusUpdate(driver sched.SchedulerDriver, status *mesos.TaskStatus) {
log.Infoln("Status update: task", status.TaskId.GetValue(), " is in state ", status.State.Enum().String())
for _, task := range sched.tasks {
if task.name == status.TaskId.GetValue() &&
(status.GetState() == mesos.TaskState_TASK_FINISHED ||
status.GetState() == mesos.TaskState_TASK_LOST ||
status.GetState() == mesos.TaskState_TASK_KILLED ||
status.GetState() == mesos.TaskState_TASK_FAILED ||
status.GetState() == mesos.TaskState_TASK_ERROR) {
// No matter what the outcome was, move to finished state so that we can unreserve resources
task.state = FinishedState
}
}
if status.GetState() == mesos.TaskState_TASK_LOST ||
status.GetState() == mesos.TaskState_TASK_KILLED ||
status.GetState() == mesos.TaskState_TASK_FAILED ||
status.GetState() == mesos.TaskState_TASK_ERROR {
log.Infoln(
"Task", status.TaskId.GetValue(),
"is in unexpected state", status.State.String(),
"with message", status.GetMessage(),
". Unreserving resources",
)
}
}
func (sched *ExampleScheduler) OfferRescinded(_ sched.SchedulerDriver, oid *mesos.OfferID) {
log.Errorf("offer rescinded: %v", oid)
}
func (sched *ExampleScheduler) FrameworkMessage(_ sched.SchedulerDriver, eid *mesos.ExecutorID, sid *mesos.SlaveID, msg string) {
log.Errorf("framework message from executor %q slave %q: %q", eid, sid, msg)
}
func (sched *ExampleScheduler) SlaveLost(_ sched.SchedulerDriver, sid *mesos.SlaveID) {
log.Errorf("slave lost: %v", sid)
}
func (sched *ExampleScheduler) ExecutorLost(_ sched.SchedulerDriver, eid *mesos.ExecutorID, sid *mesos.SlaveID, code int) {
log.Errorf("executor %q lost on slave %q code %d", eid, sid, code)
}
func (sched *ExampleScheduler) Error(_ sched.SchedulerDriver, err string) {
log.Errorf("Scheduler received error: %v", err)
}
// ----------------------- func init() ------------------------- //
func init() {
flag.Parse()
log.Infoln("Initializing the Example Scheduler...")
}
// returns (downloadURI, basename(path))
func serveExecutorArtifact(path string) (*string, string) {
serveFile := func(pattern string, filename string) {
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filename)
})
}
// Create base path (http://foobar:5000/<base>)
pathSplit := strings.Split(path, "/")
var base string
if len(pathSplit) > 0 {
base = pathSplit[len(pathSplit)-1]
} else {
base = path
}
serveFile("/"+base, path)
hostURI := fmt.Sprintf("http://%s:%d/%s", *address, *artifactPort, base)
log.V(2).Infof("Hosting artifact '%s' at '%s'", path, hostURI)
return &hostURI, base
}
func prepareExecutorInfo(id string) *mesos.ExecutorInfo {
executorUris := []*mesos.CommandInfo_URI{}
executorUris = append(executorUris, &mesos.CommandInfo_URI{Value: execUri, Executable: proto.Bool(true)})
// forward the value of the scheduler's -v flag to the executor
v := 0
if f := flag.Lookup("v"); f != nil && f.Value != nil {
if vstr := f.Value.String(); vstr != "" {
if vi, err := strconv.ParseInt(vstr, 10, 32); err == nil {
v = int(vi)
}
}
}
executorCommand := fmt.Sprintf("./%s -logtostderr=true -v=%d", execCmd, v)
go http.ListenAndServe(fmt.Sprintf("%s:%d", *address, *artifactPort), nil)
log.V(2).Info("Serving executor artifacts...")
// Create mesos scheduler driver.
return &mesos.ExecutorInfo{
ExecutorId: util.NewExecutorID(id),
Name: proto.String("Test Executor (Go)"),
Source: proto.String("go_test"),
Command: &mesos.CommandInfo{
Value: proto.String(executorCommand),
Uris: executorUris,
},
}
}
func parseIP(address string) net.IP {
addr, err := net.LookupIP(address)
if err != nil {
log.Fatal(err)
}
if len(addr) < 1 {
log.Fatalf("failed to parse IP from address '%v'", address)
}
return addr[0]
}
// ----------------------- func main() ------------------------- //
func main() {
execUri, execCmd = serveExecutorArtifact(*executorPath)
// the framework
fwinfo := &mesos.FrameworkInfo{
User: proto.String(""), // Mesos-go will fill in user.
Name: proto.String("Test Framework (Go)"),
Role: proto.String(*role),
}
cred := (*mesos.Credential)(nil)
if *mesosAuthPrincipal != "" {
fwinfo.Principal = proto.String(*mesosAuthPrincipal)
cred = &mesos.Credential{
Principal: proto.String(*mesosAuthPrincipal),
}
if *mesosAuthSecretFile != "" {
_, err := os.Stat(*mesosAuthSecretFile)
if err != nil {
log.Fatal("missing secret file: ", err.Error())
}
secret, err := ioutil.ReadFile(*mesosAuthSecretFile)
if err != nil {
log.Fatal("failed to read secret file: ", err.Error())
}
cred.Secret = proto.String(string(secret))
}
}
bindingAddress := parseIP(*address)
config := sched.DriverConfig{
Scheduler: newExampleScheduler(),
Framework: fwinfo,
Master: *master,
Credential: cred,
BindingAddress: bindingAddress,
WithAuthContext: func(ctx context.Context) context.Context {
ctx = auth.WithLoginProvider(ctx, *authProvider)
ctx = sasl.WithBindingAddress(ctx, bindingAddress)
return ctx
},
}
driver, err := sched.NewMesosSchedulerDriver(config)
if err != nil {
log.Errorln("Unable to create a SchedulerDriver ", err.Error())
}
if stat, err := driver.Run(); err != nil {
log.Infof("Framework stopped with status %s and error: %s\n", stat.String(), err.Error())
}
log.Infof("framework terminating")
}