Debian Codegraph @

api/v0/examples/scheduler/main.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 main
20
21 import (
22 "flag"
23 "fmt"
24 "io/ioutil"
25 "net"
26 "net/http"
27 "os"
28 "strconv"
29 "strings"
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/auth/sasl"
36 "github.com/mesos/mesos-go/api/v0/auth/sasl/mech"
37 mesos "github.com/mesos/mesos-go/api/v0/mesosproto"
38 util "github.com/mesos/mesos-go/api/v0/mesosutil"
39 sched "github.com/mesos/mesos-go/api/v0/scheduler"
40 "golang.org/x/net/context"
41 )
42
43 const (
44 CPUS_PER_EXECUTOR = 0.01
45 CPUS_PER_TASK = 1
46 MEM_PER_EXECUTOR = 64
47 MEM_PER_TASK = 64
48 defaultArtifactPort = 12345
49 )
50
51 var (
52 address = flag.String("address", "127.0.0.1", "Binding address for artifact server")
53 artifactPort = flag.Int("artifactPort", defaultArtifactPort, "Binding port for artifact server")
54 authProvider = flag.String("mesos_authentication_provider", sasl.ProviderName,
55 fmt.Sprintf("Authentication provider to use, default is SASL that supports mechanisms: %+v", mech.ListSupported()))
56 master = flag.String("master", "127.0.0.1:5050", "Master address <ip:port>")
57 executorPath = flag.String("executor", "./executor", "Path to test executor")
58 taskCount = flag.String("task-count", "5", "Total task count to run.")
59 mesosAuthPrincipal = flag.String("mesos_authentication_principal", "", "Mesos authentication principal.")
60 mesosAuthSecretFile = flag.String("mesos_authentication_secret_file", "", "Mesos authentication secret file.")
61 slowLaunch = flag.Bool("slow_launch", false, "When true the ResourceOffers func waits for several seconds before attempting to launch tasks; useful for debugging failover")
62 slowTasks = flag.Bool("slow_tasks", false, "When true tasks will take several seconds before responding with TASK_FINISHED; useful for debugging failover")
63 )
64
65 type ExampleScheduler struct {
66 executor *mesos.ExecutorInfo
67 tasksLaunched int
68 tasksFinished int
69 tasksErrored int
70 totalTasks int
71 }
72
73 func newExampleScheduler(exec *mesos.ExecutorInfo) *ExampleScheduler {
74 total, err := strconv.Atoi(*taskCount)
75 if err != nil {
76 total = 5
77 }
78 return &ExampleScheduler{
79 executor: exec,
80 totalTasks: total,
81 }
82 }
83
84 func (sched *ExampleScheduler) Registered(driver sched.SchedulerDriver, frameworkId *mesos.FrameworkID, masterInfo *mesos.MasterInfo) {
85 log.Infoln("Framework Registered with Master ", masterInfo)
86 }
87
88 func (sched *ExampleScheduler) Reregistered(driver sched.SchedulerDriver, masterInfo *mesos.MasterInfo) {
89 log.Infoln("Framework Re-Registered with Master ", masterInfo)
90 _, err := driver.ReconcileTasks([]*mesos.TaskStatus{})
91 if err != nil {
92 log.Errorf("failed to request task reconciliation: %v", err)
93 }
94 }
95
96 func (sched *ExampleScheduler) Disconnected(sched.SchedulerDriver) {
97 log.Warningf("disconnected from master")
98 }
99
100 func (sched *ExampleScheduler) ResourceOffers(driver sched.SchedulerDriver, offers []*mesos.Offer) {
101
102 if *slowLaunch {
103 time.Sleep(3 * time.Second)
104 }
105
106 if (sched.tasksLaunched - sched.tasksErrored) >= sched.totalTasks {
107 log.Info("decline all of the offers since all of our tasks are already launched")
108 ids := make([]*mesos.OfferID, len(offers))
109 for i, offer := range offers {
110 ids[i] = offer.Id
111 }
112 driver.LaunchTasks(ids, []*mesos.TaskInfo{}, &mesos.Filters{RefuseSeconds: proto.Float64(120)})
113 return
114 }
115 for _, offer := range offers {
116 cpuResources := util.FilterResources(offer.Resources, func(res *mesos.Resource) bool {
117 return res.GetName() == "cpus"
118 })
119 cpus := 0.0
120 for _, res := range cpuResources {
121 cpus += res.GetScalar().GetValue()
122 }
123
124 memResources := util.FilterResources(offer.Resources, func(res *mesos.Resource) bool {
125 return res.GetName() == "mem"
126 })
127 mems := 0.0
128 for _, res := range memResources {
129 mems += res.GetScalar().GetValue()
130 }
131
132 log.Infoln("Received Offer <", offer.Id.GetValue(), "> with cpus=", cpus, " mem=", mems)
133
134 remainingCpus := cpus
135 remainingMems := mems
136
137 // account for executor resources if there's not an executor already running on the slave
138 if len(offer.ExecutorIds) == 0 {
139 remainingCpus -= CPUS_PER_EXECUTOR
140 remainingMems -= MEM_PER_EXECUTOR
141 }
142
143 var tasks []*mesos.TaskInfo
144 for (sched.tasksLaunched-sched.tasksErrored) < sched.totalTasks &&
145 CPUS_PER_TASK <= remainingCpus &&
146 MEM_PER_TASK <= remainingMems {
147
148 sched.tasksLaunched++
149
150 taskId := &mesos.TaskID{
151 Value: proto.String(strconv.Itoa(sched.tasksLaunched)),
152 }
153
154 task := &mesos.TaskInfo{
155 Name: proto.String("go-task-" + taskId.GetValue()),
156 TaskId: taskId,
157 SlaveId: offer.SlaveId,
158 Executor: sched.executor,
159 Resources: []*mesos.Resource{
160 util.NewScalarResource("cpus", CPUS_PER_TASK),
161 util.NewScalarResource("mem", MEM_PER_TASK),
162 },
163 }
164 log.Infof("Prepared task: %s with offer %s for launch\n", task.GetName(), offer.Id.GetValue())
165
166 tasks = append(tasks, task)
167 remainingCpus -= CPUS_PER_TASK
168 remainingMems -= MEM_PER_TASK
169 }
170 log.Infoln("Launching ", len(tasks), "tasks for offer", offer.Id.GetValue())
171 driver.LaunchTasks([]*mesos.OfferID{offer.Id}, tasks, &mesos.Filters{RefuseSeconds: proto.Float64(5)})
172 }
173 }
174
175 func (sched *ExampleScheduler) StatusUpdate(driver sched.SchedulerDriver, status *mesos.TaskStatus) {
176 log.Infoln("Status update: task", status.TaskId.GetValue(), " is in state ", status.State.Enum().String())
177 if status.GetState() == mesos.TaskState_TASK_FINISHED {
178 sched.tasksFinished++
179 driver.ReviveOffers() // TODO(jdef) rate-limit this
180 }
181
182 if sched.tasksFinished >= sched.totalTasks {
183 log.Infoln("Total tasks completed, stopping framework.")
184 driver.Stop(false)
185 }
186
187 if status.GetState() == mesos.TaskState_TASK_LOST ||
188 status.GetState() == mesos.TaskState_TASK_KILLED ||
189 status.GetState() == mesos.TaskState_TASK_FAILED ||
190 status.GetState() == mesos.TaskState_TASK_ERROR {
191 sched.tasksErrored++
192 }
193 }
194
195 func (sched *ExampleScheduler) OfferRescinded(_ sched.SchedulerDriver, oid *mesos.OfferID) {
196 log.Errorf("offer rescinded: %v", oid)
197 }
198 func (sched *ExampleScheduler) FrameworkMessage(_ sched.SchedulerDriver, eid *mesos.ExecutorID, sid *mesos.SlaveID, msg string) {
199 log.Errorf("framework message from executor %q slave %q: %q", eid, sid, msg)
200 }
201 func (sched *ExampleScheduler) SlaveLost(_ sched.SchedulerDriver, sid *mesos.SlaveID) {
202 log.Errorf("slave lost: %v", sid)
203 }
204 func (sched *ExampleScheduler) ExecutorLost(_ sched.SchedulerDriver, eid *mesos.ExecutorID, sid *mesos.SlaveID, code int) {
205 log.Errorf("executor %q lost on slave %q code %d", eid, sid, code)
206 }
207 func (sched *ExampleScheduler) Error(_ sched.SchedulerDriver, err string) {
208 log.Errorf("Scheduler received error: %v", err)
209 }
210
211 // ----------------------- func init() ------------------------- //
212
213 func init() {
214 flag.Parse()
215 log.Infoln("Initializing the Example Scheduler...")
216 }
217
218 // returns (downloadURI, basename(path))
219 func serveExecutorArtifact(path string) (*string, string) {
220 serveFile := func(pattern string, filename string) {
221 http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
222 http.ServeFile(w, r, filename)
223 })
224 }
225
226 // Create base path (http://foobar:5000/<base>)
227 pathSplit := strings.Split(path, "/")
228 var base string
229 if len(pathSplit) > 0 {
230 base = pathSplit[len(pathSplit)-1]
231 } else {
232 base = path
233 }
234 serveFile("/"+base, path)
235
236 hostURI := fmt.Sprintf("http://%s:%d/%s", *address, *artifactPort, base)
237 log.V(2).Infof("Hosting artifact '%s' at '%s'", path, hostURI)
238
239 return &hostURI, base
240 }
241
242 func prepareExecutorInfo() *mesos.ExecutorInfo {
243 executorUris := []*mesos.CommandInfo_URI{}
244 uri, executorCmd := serveExecutorArtifact(*executorPath)
245 executorUris = append(executorUris, &mesos.CommandInfo_URI{Value: uri, Executable: proto.Bool(true)})
246
247 // forward the value of the scheduler's -v flag to the executor
248 v := 0
249 if f := flag.Lookup("v"); f != nil && f.Value != nil {
250 if vstr := f.Value.String(); vstr != "" {
251 if vi, err := strconv.ParseInt(vstr, 10, 32); err == nil {
252 v = int(vi)
253 }
254 }
255 }
256 executorCommand := fmt.Sprintf("./%s -logtostderr=true -v=%d -slow_tasks=%v", executorCmd, v, *slowTasks)
257
258 go http.ListenAndServe(fmt.Sprintf("%s:%d", *address, *artifactPort), nil)
259 log.V(2).Info("Serving executor artifacts...")
260
261 // Create mesos scheduler driver.
262 return &mesos.ExecutorInfo{
263 ExecutorId: util.NewExecutorID("default"),
264 Name: proto.String("Test Executor (Go)"),
265 Source: proto.String("go_test"),
266 Command: &mesos.CommandInfo{
267 Value: proto.String(executorCommand),
268 Uris: executorUris,
269 },
270 Resources: []*mesos.Resource{
271 util.NewScalarResource("cpus", CPUS_PER_EXECUTOR),
272 util.NewScalarResource("mem", MEM_PER_EXECUTOR),
273 },
274 }
275 }
276
277 func parseIP(address string) net.IP {
278 addr, err := net.LookupIP(address)
279 if err != nil {
280 log.Fatal(err)
281 }
282 if len(addr) < 1 {
283 log.Fatalf("failed to parse IP from address '%v'", address)
284 }
285 return addr[0]
286 }
287
288 // ----------------------- func main() ------------------------- //
289
290 func main() {
291
292 // build command executor
293 exec := prepareExecutorInfo()
294
295 // the framework
296 fwinfo := &mesos.FrameworkInfo{
297 User: proto.String(""), // Mesos-go will fill in user.
298 Name: proto.String("Test Framework (Go)"),
299 }
300
301 cred := (*mesos.Credential)(nil)
302 if *mesosAuthPrincipal != "" {
303 fwinfo.Principal = proto.String(*mesosAuthPrincipal)
304 cred = &mesos.Credential{
305 Principal: proto.String(*mesosAuthPrincipal),
306 }
307 if *mesosAuthSecretFile != "" {
308 _, err := os.Stat(*mesosAuthSecretFile)
309 if err != nil {
310 log.Fatal("missing secret file: ", err.Error())
311 }
312 secret, err := ioutil.ReadFile(*mesosAuthSecretFile)
313 if err != nil {
314 log.Fatal("failed to read secret file: ", err.Error())
315 }
316 cred.Secret = proto.String(string(secret))
317 }
318 }
319 bindingAddress := parseIP(*address)
320 config := sched.DriverConfig{
321 Scheduler: newExampleScheduler(exec),
322 Framework: fwinfo,
323 Master: *master,
324 Credential: cred,
325 BindingAddress: bindingAddress,
326 WithAuthContext: func(ctx context.Context) context.Context {
327 ctx = auth.WithLoginProvider(ctx, *authProvider)
328 ctx = sasl.WithBindingAddress(ctx, bindingAddress)
329 return ctx
330 },
331 }
332 driver, err := sched.NewMesosSchedulerDriver(config)
333
334 if err != nil {
335 log.Errorln("Unable to create a SchedulerDriver ", err.Error())
336 }
337
338 if stat, err := driver.Run(); err != nil {
339 log.Infof("Framework stopped with status %s and error: %s\n", stat.String(), err.Error())
340 time.Sleep(2 * time.Second)
341 os.Exit(1)
342 }
343 log.Infof("framework terminating")
344 }