// getMarathonClient connects to mesos cluster // returns marathon interface like tasks, applications // groups, deployment, subscriptions, ... func initMarathonClient() marathon.Marathon { config := marathon.NewDefaultConfig() config.URL = conf.New().Endpoint client, err := marathon.NewClient(config) if err != nil { glog.Fatalf("Failed to create a client for marathon, error: %s", err) } return client }
func (sc *ServerCommand) newMarathonClient(url string) (marathon.Marathon, error) { marathonConfig := marathon.NewDefaultConfig() marathonConfig.URL = url marathonClient, err := marathon.NewClient(marathonConfig) if err != nil { return nil, err } return marathonClient, nil }
// Config gives new configuration for Marathon client. func (c *Credential) Config() *marathon.Config { cfg := marathon.NewDefaultConfig() cfg.URL = c.URL cfg.HTTPBasicAuthUser = c.BasicAuthUser cfg.HTTPBasicPassword = c.BasicAuthPassword cfg.HTTPClient = &http.Client{ Timeout: c.requestTimeout() * time.Second, } return &cfg }
func main() { config := marathon.NewDefaultConfig() config.URL = marathonURL client, err := marathon.NewClient(config) if err != nil { log.Fatalf("Make new marathon client error: %v", err) } app := marathon.Application{} app.ID = "queue-test" app.Command("sleep 5") app.Count(1) app.Memory(32) fmt.Println("Creating/updating app.") // Update application will either create or update the app. _, err = client.UpdateApplication(&app, false) if err != nil { log.Fatalf("Update application error: %v", err) } // wait until marathon will launch tasks err = client.WaitOnApplication(app.ID, 10*time.Second) if err != nil { log.Fatalln("Application deploy failure, timeout.") } fmt.Println("Application was deployed.") // get marathon queue by chance for i := 0; i < 30; i++ { // Avoid shadowing err from outer scope. var queue *marathon.Queue queue, err = client.Queue() if err != nil { log.Fatalf("Get queue error: %v\n", err) } if len(queue.Items) > 0 { fmt.Println(queue) break } fmt.Printf("Queue is blank now, retry(%d)...\n", 30-i) time.Sleep(time.Second) } // delete marathon queue delay err = client.DeleteQueueDelay(app.ID) if err != nil { log.Fatalf("Delete queue delay error: %v\n", err) } fmt.Println("Queue delay deleted.") return }
// getMarathonClient connects to mesos cluster // returns marathon interface like tasks, applications // groups, deployment, subscriptions, ... func initMarathonClient() marathon.Marathon { config := marathon.NewDefaultConfig() chimpConfig := conf.New() config.URL = chimpConfig.Endpoint if chimpConfig.MarathonAuth.Enabled { config.HTTPBasicAuthUser = chimpConfig.MarathonAuth.MarathonHttpUser config.HTTPBasicPassword = chimpConfig.MarathonAuth.MarathonHttpPassword } client, err := marathon.NewClient(config) if err != nil { glog.Fatalf("Failed to create a client for marathon, error: %s", err) } return client }
// New creates a new Adapter. func New(marathonURL string) (*Adapter, error) { config := marathonClient.NewDefaultConfig() config.URL = marathonURL config.EventsTransport = marathonClient.EventsTransportSSE log.WithField("prefix", "marathon").Infof("Connecting to Marathon at %v", marathonURL) client, err := marathonClient.NewClient(config) if err != nil { return nil, err } return &Adapter{ client: client, resolver: &defaultAddressResolver{}, }, nil }
func main() { flag.Parse() config := marathon.NewDefaultConfig() config.URL = marathon_url config.LogOutput = os.Stdout config.EventsPort = marathon_port config.EventsInterface = marathon_interface glog.Infof("Creating a client Marathon: %s", marathon_url) client, err := marathon.NewClient(config) Assert(err) /* step: lets register for events */ events := make(marathon.EventsChannel, 5) deployments := make(marathon.EventsChannel, 5) Assert(client.AddEventsListener(events, marathon.EVENTS_APPLICATIONS)) Assert(client.AddEventsListener(deployments, marathon.EVENT_DEPLOYMENT_STEP_SUCCESS)) // lets listen for 10 seconds and then split timer := time.After(time.Duration(timeout) * time.Second) kill_off := false for { if kill_off { break } select { case <-timer: glog.Infof("Exitting the loop") kill_off = true case event := <-events: glog.Infof("Recieved application event: %s", event) case event := <-deployments: glog.Infof("Recieved deployment event: %v", event) var deployment *marathon.EventDeploymentStepSuccess deployment = event.Event.(*marathon.EventDeploymentStepSuccess) glog.Infof("deployment step:: %v", deployment.CurrentStep) } } glog.Infof("Removing our subscription") client.RemoveEventsListener(events) client.RemoveEventsListener(deployments) Assert(client.UnSubscribe()) }
func main() { flag.Parse() config := marathon.NewDefaultConfig() config.URL = marathonURL client, err := marathon.NewClient(config) if err != nil { log.Fatalf("Failed to create a client for marathon, error: %s", err) } for { if application, err := client.Applications(nil); err != nil { log.Fatalf("Failed to retrieve a list of applications, error: %s", err) } else { log.Printf("Retrieved a list of applications, %v", application) } log.Printf("Going to sleep for %s\n", waitTime) time.Sleep(waitTime) } }
func main() { flag.Parse() config := marathon.NewDefaultConfig() config.URL = marathonURL client, err := marathon.NewClient(config) if err != nil { glog.Fatalf("Failed to create a client for marathon, error: %s", err) } for { if application, err := client.Applications(nil); err != nil { glog.Errorf("Failed to retrieve a list of applications, error: %s", err) } else { glog.Infof("Retrieved a list of applications, %v", application) } glog.Infof("Going to sleep for 20 seconds") time.Sleep(5 * time.Second) } }
func appList(cmd *cli.Cmd) { cmd.Action = func() { output := tm.NewTable(0, 5, 2, ' ', 0) config := marathon.NewDefaultConfig() config.URL = *marathonHost client, err := marathon.NewClient(config) if err != nil { panic(err) } applications, err := client.Applications(nil) if err != nil { panic(err) } for i, application := range applications.Apps { color := chalk.White health := "" if i != 0 { fmt.Fprint(output, "\n") } if application.HasHealthChecks() { if healthy, _ := client.ApplicationOK(application.ID); healthy { color = chalk.Green health = "Ok" } else { color = chalk.Red health = "Failing" } } fmt.Fprintf(output, "%s%s \t %d/%d/%d \t%s%s", color, application.ID, application.TasksRunning, application.TasksStaged, application.Instances, health, chalk.Reset) } tm.Print(output) tm.Flush() } }
func main() { flag.Parse() config := marathon.NewDefaultConfig() config.URL = marathonURL config.LogOutput = new(logBridge) client, err := marathon.NewClient(config) if err != nil { glog.Exitln(err) } applications, err := client.Applications(nil) if err != nil { glog.Exitln(err) } for _, a := range applications.Apps { glog.Infof("App ID: %v\n", a.ID) } }
func main() { flag.Parse() config := marathon.NewDefaultConfig() config.URL = marathonURL config.EventsInterface = marathonInterface config.EventsPort = marathonPort log.Printf("Creating a client, Marathon: %s", marathonURL) client, err := marathon.NewClient(config) assert(err) // Register for events events := make(marathon.EventsChannel, 5) deployments := make(marathon.EventsChannel, 5) assert(client.AddEventsListener(events, marathon.EventIDApplications)) assert(client.AddEventsListener(deployments, marathon.EventIDDeploymentStepSuccess)) // Listen for x seconds and then split timer := time.After(time.Duration(timeout) * time.Second) done := false for { if done { break } select { case <-timer: log.Printf("Exiting the loop") done = true case event := <-events: log.Printf("Recieved application event: %s", event) case event := <-deployments: log.Printf("Recieved deployment event: %v", event) var deployment *marathon.EventDeploymentStepSuccess deployment = event.Event.(*marathon.EventDeploymentStepSuccess) log.Printf("deployment step: %v", deployment.CurrentStep) } } log.Printf("Removing our subscription") client.RemoveEventsListener(events) client.RemoveEventsListener(deployments) }
//Deploy deploys the marathon app func (dep *MarathonDeployer) Deploy(jsonContent []byte) (*ExpectedDeployment, error) { if app, err := parseContent(jsonContent); err == nil { config := marathon.NewDefaultConfig() config.URL = dep.URL config.LogOutput = os.Stdout if client, err := marathon.NewClient(config); err == nil { if alreadyExists, err := client.HasApplication(app.ID); err == nil && alreadyExists { return updateApplication(client, app) } else if err == nil && !alreadyExists { return createNewApplication(client, app) } else { return nil, err } } else { glog.Fatalf("Failed to create a client for marathon, error: %s", err) return nil, err } } return nil, nil }
func main() { config := marathon.NewDefaultConfig() config.URL = marathonURL client, err := marathon.NewClient(config) if err != nil { panic(err) } app := marathon.Application{} app.ID = "tasks-test" app.Command("sleep 60") app.Count(3) fmt.Println("Creating app.") // Update application will either create or update the app. _, err = client.UpdateApplication(&app, false) if err != nil { panic(err) } // wait until marathon will launch tasks client.WaitOnApplication(app.ID, 10*time.Second) fmt.Println("Tasks were deployed.") tasks, err := client.Tasks(app.ID) if err != nil { panic(err) } host := tasks.Tasks[0].Host fmt.Printf("Killing tasks on the host: %s\n", host) _, err = client.KillApplicationTasks(app.ID, &marathon.KillApplicationTasksOpts{Scale: true, Host: host}) if err != nil { panic(err) } }
func MarathonClient(marathonAddress string) (marathon.Marathon, error) { conf := marathon.NewDefaultConfig() conf.URL = fmt.Sprintf("http://%s", marathonAddress) conf.LogOutput = os.Stderr return marathon.NewClient(conf) }
func main() { flag.Parse() config := marathon.NewDefaultConfig() config.URL = marathonURL client, err := marathon.NewClient(config) if err != nil { log.Fatalf("Failed to create a client for marathon, error: %s", err) } log.Printf("Retrieving a list of groups") if groups, err := client.Groups(); err != nil { log.Fatalf("Failed to retrieve the groups from maratho, error: %s", err) } else { for _, group := range groups.Groups { log.Printf("Found group: %s", group.ID) } } groupName := "/product/group" found, err := client.HasGroup(groupName) assert(err) if found { log.Printf("Deleting the group: %s, as it already exists", groupName) id, err := client.DeleteGroup(groupName) assert(err) err = client.WaitOnDeployment(id.DeploymentID, 0) assert(err) } /* step: the frontend app */ frontend := marathon.NewDockerApplication() frontend.Name("/product/group/frontend") frontend.CPU(0.1).Memory(64).Storage(0.0).Count(2) frontend.Arg("/usr/sbin/apache2ctl").Arg("-D").Arg("FOREGROUND") frontend.AddEnv("NAME", "frontend_http") frontend.AddEnv("SERVICE_80_NAME", "frontend_http") frontend.AddEnv("SERVICE_443_NAME", "frontend_https") frontend.AddEnv("BACKEND_MYSQL", "/product/group/mysql/3306;3306") frontend.AddEnv("BACKEND_CACHE", "/product/group/cache/6379;6379") frontend.DependsOn("/product/group/cache") frontend.DependsOn("/product/group/mysql") frontend.Container.Docker.Container("quay.io/gambol99/apache-php:latest").Expose(80).Expose(443) _, err = frontend.CheckHTTP("/hostname.php", 80, 10) assert(err) mysql := marathon.NewDockerApplication() mysql.Name("/product/group/mysql") mysql.CPU(0.1).Memory(128).Storage(0.0).Count(1) mysql.AddEnv("NAME", "group_cache") mysql.AddEnv("SERVICE_3306_NAME", "mysql") mysql.AddEnv("MYSQL_PASS", "mysql") mysql.Container.Docker.Container("tutum/mysql").Expose(3306) _, err = mysql.CheckTCP(3306, 10) assert(err) redis := marathon.NewDockerApplication() redis.Name("/product/group/cache") redis.CPU(0.1).Memory(64).Storage(0.0).Count(2) redis.AddEnv("NAME", "group_cache") redis.AddEnv("SERVICE_6379_NAME", "redis") redis.Container.Docker.Container("redis:latest").Expose(6379) _, err = redis.CheckTCP(6379, 10) assert(err) group := marathon.NewApplicationGroup(groupName) group.App(frontend).App(redis).App(mysql) assert(client.CreateGroup(group)) log.Printf("Successfully created the group: %s", group.ID) log.Printf("Updating the group paramaters") frontend.Count(4) id, err := client.UpdateGroup(groupName, group) assert(err) log.Printf("Successfully updated the group: %s, version: %s", group.ID, id.DeploymentID) assert(client.WaitOnGroup(groupName, 500*time.Second)) }
func main() { flag.Parse() config := marathon.NewDefaultConfig() config.URL = marathon_url config.LogOutput = os.Stdout client, err := marathon.NewClient(config) Assert(err) applications, err := client.Applications(nil) Assert(err) glog.Infof("Found %d application running", len(applications.Apps)) for _, application := range applications.Apps { glog.Infof("Application: %s", application) details, err := client.Application(application.ID) Assert(err) if details.Tasks != nil && len(details.Tasks) > 0 { for _, task := range details.Tasks { glog.Infof("task: %s", task) } health, err := client.ApplicationOK(details.ID) Assert(err) glog.Infof("Application: %s, healthy: %t", details.ID, health) } } APPLICATION_NAME := "/my/product" if found, _ := client.HasApplication(APPLICATION_NAME); found { deployId, err := client.DeleteApplication(APPLICATION_NAME) Assert(err) waitOnDeployment(client, deployId) } glog.Infof("Deploying a new application") application := marathon.NewDockerApplication() application.Name(APPLICATION_NAME) application.CPU(0.1).Memory(64).Storage(0.0).Count(2) application.Arg("/usr/sbin/apache2ctl").Arg("-D").Arg("FOREGROUND") application.AddEnv("NAME", "frontend_http") application.AddEnv("SERVICE_80_NAME", "test_http") application.RequirePorts = true application.Container.Docker.Container("quay.io/gambol99/apache-php:latest").Expose(80).Expose(443) _, err = client.CreateApplication(application) Assert(err) glog.Infof("Scaling the application to 4 instances") deployId, err := client.ScaleApplicationInstances(application.ID, 4, false) Assert(err) client.WaitOnApplication(application.ID, 30*time.Second) glog.Infof("Successfully scaled the application, deployId: %s", deployId.DeploymentID) glog.Infof("Deleting the application: %s", APPLICATION_NAME) deployId, err = client.DeleteApplication(application.ID) Assert(err) time.Sleep(time.Duration(10) * time.Second) glog.Infof("Successfully deleted the application") glog.Infof("Starting the application again") _, err = client.CreateApplication(application) Assert(err) glog.Infof("Created the application: %s", application.ID) glog.Infof("Delete all the tasks") _, err = client.KillApplicationTasks(application.ID, "", false) Assert(err) }
func main() { flag.Parse() config := marathon.NewDefaultConfig() config.URL = marathonURL client, err := marathon.NewClient(config) assert(err) applications, err := client.Applications(nil) assert(err) log.Printf("Found %d application running", len(applications.Apps)) for _, application := range applications.Apps { log.Printf("Application: %v", application) details, err := client.Application(application.ID) assert(err) if details.Tasks != nil && len(details.Tasks) > 0 { for _, task := range details.Tasks { log.Printf("task: %v", task) } health, err := client.ApplicationOK(details.ID) assert(err) log.Printf("Application: %s, healthy: %t", details.ID, health) } } applicationName := "/my/product" if _, err := client.Application(applicationName); err == nil { deployID, err := client.DeleteApplication(applicationName, false) assert(err) waitOnDeployment(client, deployID) } log.Printf("Deploying a new application") application := marathon.NewDockerApplication(). Name(applicationName). CPU(0.1). Memory(64). Storage(0.0). Count(2). AddArgs("/usr/sbin/apache2ctl", "-D", "FOREGROUND"). AddEnv("NAME", "frontend_http"). AddEnv("SERVICE_80_NAME", "test_http") application. Container.Docker.Container("quay.io/gambol99/apache-php:latest"). Bridged(). Expose(80). Expose(443) *application.RequirePorts = true _, err = client.CreateApplication(application) assert(err) client.WaitOnApplication(application.ID, 30*time.Second) log.Printf("Scaling the application to 4 instances") deployID, err := client.ScaleApplicationInstances(application.ID, 4, false) assert(err) client.WaitOnApplication(application.ID, 30*time.Second) log.Printf("Successfully scaled the application, deployID: %s", deployID.DeploymentID) log.Printf("Deleting the application: %s", applicationName) deployID, err = client.DeleteApplication(application.ID, true) assert(err) waitOnDeployment(client, deployID) log.Printf("Successfully deleted the application") log.Printf("Starting the application again") _, err = client.CreateApplication(application) assert(err) log.Printf("Created the application: %s", application.ID) log.Printf("Delete all the tasks") _, err = client.KillApplicationTasks(application.ID, nil) assert(err) }
func appInfo(cmd *cli.Cmd) { cmd.Spec = "NAME" var ( name = cmd.StringArg("NAME", "", "") ) cmd.Action = func() { config := marathon.NewDefaultConfig() config.URL = *marathonHost client, err := marathon.NewClient(config) if err != nil { fmt.Print("Can't connect to marathon\n") os.Exit(1) } application, err := client.Application(*name) if err != nil { fmt.Print("Application doesn't exists\n") os.Exit(1) } output := tm.NewTable(0, 2, 1, ' ', 0) //output := os.Stdout fmt.Fprint(output, "\n") fmt.Fprintf(output, "Application Name: \t\"%s\"\n", application.ID) fmt.Fprintf(output, "Running/Staged/Failing/Requested: \t%d/%d/%d/%d\n", application.TasksRunning, application.TasksStaged, application.TasksUnhealthy, application.Instances) if application.TasksRunning > 0 { fmt.Fprint(output, "\nRunning tasks:\n") for _, task := range application.Tasks { if application.HasHealthChecks() { var alive bool for _, result := range task.HealthCheckResult { alive = result.Alive } // TODO: Support multiple ports if alive { fmt.Fprintf(output, "%s - %s:%d \t Ok%s\n", chalk.Green, task.Host, task.Ports[0], chalk.Reset) } else { fmt.Fprintf(output, "%s - %s:%d \t Failing%s\n", chalk.Red, task.Host, task.Ports[0], chalk.Reset) } } else { fmt.Fprintf(output, " - %s:%d\n", task.Host, task.Ports[0]) } } } else { fmt.Fprint(output, " - Exposed ports: \tNo\n") } fmt.Fprint(output, "\nHealthcheck Information:\n") fmt.Fprintf(output, " - Has Healthcheck? : \t%t\n", application.HasHealthChecks()) if application.HasHealthChecks() { if healthy, _ := client.ApplicationOK(application.ID); healthy { fmt.Fprintf(output, " - Healthcheck Status: \t%sOk%s\n", chalk.Green, chalk.Reset) } else { fmt.Fprintf(output, " - Healthcheck Status: \t%sFailing%s\n", chalk.Red, chalk.Reset) } for i, healthcheck := range application.HealthChecks { fmt.Fprintf(output, "\nHealthcheck num: %d\n", i+1) fmt.Fprintf(output, " - Protocol: \t%s\n", healthcheck.Protocol) if healthcheck.Protocol == "COMMAND" { fmt.Fprintf(output, " - Command: \t%s\n", healthcheck.Command.Value) } else { fmt.Fprintf(output, " - Path: \t%s\n", healthcheck.Path) } fmt.Fprintf(output, " - Grace period seconds: \t%ds\n", healthcheck.GracePeriodSeconds) fmt.Fprintf(output, " - Interval: \t%ds\n", healthcheck.IntervalSeconds) fmt.Fprintf(output, " - Timeout: \t%ds\n", healthcheck.TimeoutSeconds) fmt.Fprintf(output, " - Max consecutive failures: \t%d\n", healthcheck.MaxConsecutiveFailures) } } tm.Print(output) tm.Flush() output = tm.NewTable(0, 2, 1, ' ', 0) taskRunningF := float64(application.TasksRunning) fmt.Fprint(output, "Per instance limits:\n") fmt.Fprintf(output, " - CPU shares: \t%.1f \t(%.1f)\n", application.CPUs, application.CPUs*taskRunningF) fmt.Fprintf(output, " - Memory: \t%.1f \t(%.1f)\n", application.Mem, application.Mem*taskRunningF) fmt.Fprintf(output, " - Disk: \t%.1f \t(%.1f)\n", application.Disk, application.Disk*taskRunningF) fmt.Fprint(output, "\nUpgrade strategy:\n") fmt.Fprintf(output, " - Maximum over capacity: \t%3.f%% \n", application.UpgradeStrategy.MaximumOverCapacity*100) fmt.Fprintf(output, " - Minimum health capacity: \t%3.f%% \n", application.UpgradeStrategy.MinimumHealthCapacity*100) fmt.Fprint(output, "\nEnv vars:\n") for k := range application.Env { fmt.Fprintf(output, " - %s = \"%s\" \n", k, application.Env[k]) } tm.Print(output) tm.Flush() } }
func appUpdate(cmd *cli.Cmd) { cmd.Spec = "NAME [--instances=<num> | --cpu=<num> |--mem=<num> | --docker-image=<image>]" // healthCheckCMD = cmd.StringOpt("command-healthcheck", "", "Command to use as healthcheck") // healthCheckHTTP = cmd.StringOpt("http-healthcheck", "", "HTTP path to use as healthcheck") // healthCheckTCP = cmd.IntOpt("tcp-healthcheck", -1, "TCP port to use as healthcheck") var ( instances = cmd.IntOpt("instances", 0, "Number of instances") dockerImage = cmd.StringOpt("docker-image", "", "Docker image and version") cpu = cmd.StringOpt("cpu", "", "cpu shares") mem = cmd.StringOpt("mem", "", "memory mb limit") name = cmd.StringArg("NAME", "", "Application name") ) cmd.Action = func() { config := marathon.NewDefaultConfig() config.URL = *marathonHost client, err := marathon.NewClient(config) application, err := client.Application(*name) application.Version = "" output := tm.NewTable(0, 2, 1, ' ', 0) // if *healthCheckCMD != "" { // // } // // if *healthCheckHTTP != "" { // // } // // if *healthCheckTCP != -1 { // // } if *dockerImage != "" { fmt.Fprintf(output, "Setting new docker image:\t %s \t-> %s\n", application.Container.Docker.Image, *dockerImage) application.Container.Docker.Container(*dockerImage) } if *cpu != "" { cpuFloat, _ := strconv.ParseFloat(*cpu, 64) fmt.Fprintf(output, "Setting new cpu limits:\t %.3f \t-> %.3f\n", application.CPUs, cpuFloat) application.CPU(cpuFloat) if err != nil { panic(err) } } if *mem != "" { memFloat, _ := strconv.ParseFloat(*mem, 64) fmt.Fprintf(output, "Setting new memory limits:\t %.1f \t-> %.1f\n", application.Mem, memFloat) application.Memory(memFloat) if err != nil { panic(err) } } if *instances != 0 { fmt.Fprintf(output, "Setting new number of instances:\t %d \t-> %d\n", application.Instances, *instances) application.Count(*instances) } deployment, err := client.UpdateApplication(application) if err != nil { panic(err) } tm.Print(output) tm.Flush() fmt.Fprintf(os.Stdout, "Starting deployment: %s\n", deployment.DeploymentID) client.WaitOnApplication(application.ID, 60*time.Second) fmt.Println("Application deployed!") } }