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
|
/**
* 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"
"time"
"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_EXECUTOR = 0.01
CPUS_PER_TASK = 1
MEM_PER_EXECUTOR = 64
MEM_PER_TASK = 64
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.")
mesosAuthPrincipal = flag.String("mesos_authentication_principal", "", "Mesos authentication principal.")
mesosAuthSecretFile = flag.String("mesos_authentication_secret_file", "", "Mesos authentication secret file.")
slowLaunch = flag.Bool("slow_launch", false, "When true the ResourceOffers func waits for several seconds before attempting to launch tasks; useful for debugging failover")
slowTasks = flag.Bool("slow_tasks", false, "When true tasks will take several seconds before responding with TASK_FINISHED; useful for debugging failover")
)
type ExampleScheduler struct {
executor *mesos.ExecutorInfo
tasksLaunched int
tasksFinished int
tasksErrored int
totalTasks int
}
func newExampleScheduler(exec *mesos.ExecutorInfo) *ExampleScheduler {
total, err := strconv.Atoi(*taskCount)
if err != nil {
total = 5
}
return &ExampleScheduler{
executor: exec,
totalTasks: total,
}
}
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)
_, err := driver.ReconcileTasks([]*mesos.TaskStatus{})
if err != nil {
log.Errorf("failed to request task reconciliation: %v", err)
}
}
func (sched *ExampleScheduler) Disconnected(sched.SchedulerDriver) {
log.Warningf("disconnected from master")
}
func (sched *ExampleScheduler) ResourceOffers(driver sched.SchedulerDriver, offers []*mesos.Offer) {
if *slowLaunch {
time.Sleep(3 * time.Second)
}
if (sched.tasksLaunched - sched.tasksErrored) >= sched.totalTasks {
log.Info("decline all of the offers since all of our tasks are already launched")
ids := make([]*mesos.OfferID, len(offers))
for i, offer := range offers {
ids[i] = offer.Id
}
driver.LaunchTasks(ids, []*mesos.TaskInfo{}, &mesos.Filters{RefuseSeconds: proto.Float64(120)})
return
}
for _, offer := range offers {
cpuResources := util.FilterResources(offer.Resources, func(res *mesos.Resource) bool {
return res.GetName() == "cpus"
})
cpus := 0.0
for _, res := range cpuResources {
cpus += res.GetScalar().GetValue()
}
memResources := util.FilterResources(offer.Resources, func(res *mesos.Resource) bool {
return res.GetName() == "mem"
})
mems := 0.0
for _, res := range memResources {
mems += res.GetScalar().GetValue()
}
log.Infoln("Received Offer <", offer.Id.GetValue(), "> with cpus=", cpus, " mem=", mems)
remainingCpus := cpus
remainingMems := mems
// account for executor resources if there's not an executor already running on the slave
if len(offer.ExecutorIds) == 0 {
remainingCpus -= CPUS_PER_EXECUTOR
remainingMems -= MEM_PER_EXECUTOR
}
var tasks []*mesos.TaskInfo
for (sched.tasksLaunched-sched.tasksErrored) < sched.totalTasks &&
CPUS_PER_TASK <= remainingCpus &&
MEM_PER_TASK <= remainingMems {
sched.tasksLaunched++
taskId := &mesos.TaskID{
Value: proto.String(strconv.Itoa(sched.tasksLaunched)),
}
task := &mesos.TaskInfo{
Name: proto.String("go-task-" + taskId.GetValue()),
TaskId: taskId,
SlaveId: offer.SlaveId,
Executor: sched.executor,
Resources: []*mesos.Resource{
util.NewScalarResource("cpus", CPUS_PER_TASK),
util.NewScalarResource("mem", MEM_PER_TASK),
},
}
log.Infof("Prepared task: %s with offer %s for launch\n", task.GetName(), offer.Id.GetValue())
tasks = append(tasks, task)
remainingCpus -= CPUS_PER_TASK
remainingMems -= MEM_PER_TASK
}
log.Infoln("Launching ", len(tasks), "tasks for offer", offer.Id.GetValue())
driver.LaunchTasks([]*mesos.OfferID{offer.Id}, tasks, &mesos.Filters{RefuseSeconds: proto.Float64(5)})
}
}
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())
if status.GetState() == mesos.TaskState_TASK_FINISHED {
sched.tasksFinished++
driver.ReviveOffers() // TODO(jdef) rate-limit this
}
if sched.tasksFinished >= sched.totalTasks {
log.Infoln("Total tasks completed, stopping framework.")
driver.Stop(false)
}
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 {
sched.tasksErrored++
}
}
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() *mesos.ExecutorInfo {
executorUris := []*mesos.CommandInfo_URI{}
uri, executorCmd := serveExecutorArtifact(*executorPath)
executorUris = append(executorUris, &mesos.CommandInfo_URI{Value: uri, 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 -slow_tasks=%v", executorCmd, v, *slowTasks)
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("default"),
Name: proto.String("Test Executor (Go)"),
Source: proto.String("go_test"),
Command: &mesos.CommandInfo{
Value: proto.String(executorCommand),
Uris: executorUris,
},
Resources: []*mesos.Resource{
util.NewScalarResource("cpus", CPUS_PER_EXECUTOR),
util.NewScalarResource("mem", MEM_PER_EXECUTOR),
},
}
}
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() {
// build command executor
exec := prepareExecutorInfo()
// the framework
fwinfo := &mesos.FrameworkInfo{
User: proto.String(""), // Mesos-go will fill in user.
Name: proto.String("Test Framework (Go)"),
}
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(exec),
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())
time.Sleep(2 * time.Second)
os.Exit(1)
}
log.Infof("framework terminating")
}
|