Пример #1
0
func (applist AppList) Run(c CommandConfigs) (bool, string) {
	var resp *http.Response
	var bodyStr string
	resp = c.Run()
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.Status == "200 OK" {
		bodyStr = string(body)
		var errorFormat formats.ErrorFormat
		err := json.Unmarshal([]byte(bodyStr), &errorFormat)
		if err == nil {
			//<TODO> Make these error checking functionality common
			if errorFormat.ErrorCode == http.StatusUnauthorized {
				fmt.Println("Your session has expired.Please login and try again!")
			}
		} else {
			var apps []formats.AppFormat
			err := json.Unmarshal([]byte(bodyStr), &apps)
			if err == nil {
				fmt.Println("You have ", len(apps), " applications. Details of applications are as follows.\n")
				totals := tm.NewTable(0, 10, 5, ' ', 0)
				fmt.Fprintf(totals, "Name\tKey\tType\tDescription\n")
				fmt.Fprintf(totals, "----\t---\t----\t-----------\n")
				for _, app := range apps {
					fmt.Fprintf(totals, "%s\t%s\t%s\t%s\n", app.Name, app.Key, app.Type, app.Description)
				}
				tm.Println(totals)
				tm.Flush()
			}

		}
	}
	return true, c.Cookie
}
Пример #2
0
func printHosts(lastApiResponse *healthd.ApiResponseHosts, status *healthdStatus) {
	goterm.Clear() // Clear current screen
	goterm.MoveCursor(1, 1)
	defer goterm.Flush()
	goterm.Println("Current Time:", status.FmtNow(), "   Status:", status.FmtStatus())

	//
	if lastApiResponse == nil {
		goterm.Println("no data yet")
		return
	}

	columns := []string{
		"Host:Port",
		"Status",
		"Last Checked",
		"Last Response Time",
	}

	for i, s := range columns {
		columns[i] = goterm.Bold(goterm.Color(s, goterm.BLACK))
	}

	table := goterm.NewTable(0, goterm.Width()-1, 5, ' ', 0)
	fmt.Fprintf(table, "%s\n", strings.Join(columns, "\t"))

	for _, host := range lastApiResponse.Hosts {
		printHost(table, host)
	}

	goterm.Println(table)
}
Пример #3
0
Файл: main.go Проект: rmg/tyk
// Display configuration options
func displayConfig() {
	configTable := goterm.NewTable(0, 10, 5, ' ', 0)
	fmt.Fprintf(configTable, "Listening on port:\t%d\n", config.ListenPort)

	fmt.Println(configTable)
	fmt.Println("")
}
Пример #4
0
/* Run calls the Run function of CommandConfigs and verifies the response from that call.*/
func (appInfo AppInfo) Run(configs CommandConfigs) (bool, string) {
	resp := configs.Run()
	//if request did not fail
	if resp != nil {
		defer resp.Body.Close()
	} else {
		//exit the cli
		return true, ""
	}
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode == http.StatusOK {
		bodyString := string(body)
		var errorFormat formats.ErrorFormat
		err := json.Unmarshal([]byte(bodyString), &errorFormat)
		if err == nil {
			if errorFormat.ErrorCode == http.StatusUnauthorized {
				fmt.Println("Your session has expired.Please login and try again!")
				return false, configs.Cookie
			}
		}
		var app formats.App
		err = json.Unmarshal([]byte(bodyString), &app)
		if err == nil {
			// Display application details in tabular format
			fmt.Println("\nDetails of application are as follows.\n")
			totals := tableManagement.NewTable(0, 10, 5, ' ', 0)
			fmt.Fprintf(totals, "Name\tKey\tType\tRepositoryType\tOwner\n")
			fmt.Fprintf(totals, "-------\t------\t-----\t---------\t----------------\n")
			fmt.Fprintf(totals, "%s\t%s\t%s\t%s\t%s\n", app.Name, app.Key, app.Type, app.RepositoryType, app.Owner)
			tableManagement.Println(totals)
			tableManagement.Flush()
		}
	}
	return true, configs.Cookie
}
Пример #5
0
func (appInfo AppInfo) Run(c CommandConfigs) (bool, string) {
	var resp *http.Response
	var bodyStr string
	resp = c.Run()
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.Status == "200 OK" {
		bodyStr = string(body)
		var errorFormat formats.ErrorFormat
		err := json.Unmarshal([]byte(bodyStr), &errorFormat)
		if err == nil {
			//<TODO> Make these error checking functionality common
			if errorFormat.ErrorCode == http.StatusUnauthorized {
				fmt.Println("Your session has expired.Please login and try again!")
			}
			println("has error")
		}
		var app formats.AppFormat
		err = json.Unmarshal([]byte(bodyStr), &app)
		if err == nil {
			fmt.Println("\nDetails of application are as follows.\n")
			totals := tm.NewTable(0, 10, 5, ' ', 0)
			fmt.Fprintf(totals, "Name\tKey\tType\tRepositoryType\tOwner\n")
			fmt.Fprintf(totals, "-------\t------\t-----\t---------\t----------------\n")
			fmt.Fprintf(totals, "%s\t%s\t%s\t%s\t%s\n", app.Name, app.Key, app.Type, app.RepositoryType, app.Owner)
			tm.Println(totals)
			tm.Flush()
		}

	}
	return true, c.Cookie
}
Пример #6
0
func serversOverview(servers []engine.Server) string {
	t := goterm.NewTable(0, 10, 5, ' ', 0)
	fmt.Fprint(t, "Id\tURL\tReqs/sec\t50ile[ms]\t95ile[ms]\t99ile[ms]\tStatus codes %%\tNet. errors %%\tMessages\n")

	for _, e := range servers {
		serverOverview(t, e)
	}
	return t.String()
}
Пример #7
0
func frontendsOverview(frontends []engine.Frontend) string {
	t := goterm.NewTable(0, 10, 5, ' ', 0)
	fmt.Fprint(t, "Id\tRoute\tR/sec\t50ile[ms]\t95ile[ms]\t99ile[ms]\tStatus codes %%\tNet. errors %%\n")

	if len(frontends) == 0 {
		return t.String()
	}
	for _, l := range frontends {
		frontendOverview(t, l)
	}
	return t.String()
}
Пример #8
0
func alertsCmd(cmd *cobra.Command, args []string) {
	createClient()

	params := wavefront.QueryParams{}

	if customerTag != "" {
		params["customerTag"] = customerTag
	}

	if userTag != "" {
		params["userTag"] = userTag
	}

	// parse the args to ascertain which function to use
	var f func(*wavefront.QueryParams) ([]*wavefront.Alert, error)
	if len(args) == 0 || args[0] == "all" {
		f = client.Alerts.All
	} else {
		switch args[0] {
		case "all":
			f = client.Alerts.All
		case "snoozed":
			f = client.Alerts.Snoozed
		case "firing":
			f = client.Alerts.Active
		case "invalid":
			f = client.Alerts.Invalid
		case "affected_by_maintenance":
			f = client.Alerts.AffectedByMaintenance
		default:
			log.Fatal("Please provide a valid alert type.")
		}
	}

	alerts, err := f(&params)
	if err != nil {
		log.Fatal(err)
	}

	if rawResponse == true {
		prettyPrint(&client.Alerts.RawResponse)
	} else {

		table := goterm.NewTable(0, 10, 5, ' ', 0)
		fmt.Fprintf(table, "Name\tSeverity\n")
		for _, a := range alerts {
			fmt.Fprintf(table, "%s\t%s\n", a.Name, a.Severity)
		}
		goterm.Println(table)
		goterm.Flush()
	}
}
Пример #9
0
func main() {
	tm.Clear() // Clear current screen
	started := 100
	finished := 250

	// Based on http://golang.org/pkg/text/tabwriter
	totals := tm.NewTable(0, 10, 5, ' ', 0)
	fmt.Fprintf(totals, "Time\tStarted\tActive\tFinished\n")
	fmt.Fprintf(totals, "%s\t%d\t%d\t%d\n", "All", started, started-finished, finished)
	tm.Println(totals)

	tm.Flush()
}
Пример #10
0
func ToolHelp(factory command.CommandFactory) {
	fmt.Println("\n" + Bold("NAME") + " : appfac\n")
	fmt.Println(Bold("USAGE") + " : CLI Tool for WSO2 Appfactory\n")
	fmt.Println(Bold("VERSION") + " : 1.0.0\n")
	fmt.Println(Bold("COMMANDS") + " :\n")

	commands := tablemanagement.NewTable(0, 10, 5, ' ', 0)
	fmt.Fprintf(commands, "%s\t%s\t%s\n", "help", "h", "Shows help for appfac CLI tool")
	for _, command := range factory.CmdsByName {
		metadata := command.Metadata()
		fmt.Fprintf(commands, "%s\t%s\t%s\n", metadata.Name, metadata.ShortName, metadata.Description)
	}
	fmt.Fprintf(commands, "%s\t%s\t%s\n", command.SetBaseUrlCommand, command.SetBaseUrlCommand, "Sets base url for the tool")
	tablemanagement.Println(commands)
	tablemanagement.Flush()
}
Пример #11
0
func HelpTemplate(metadata command.CommandMetadata) {
	commandHelp := tablemanagement.NewTable(0, 10, 5, ' ', 0)
	fmt.Fprintf(commandHelp, "%s\t%s\n", Bold("COMMAND"), metadata.Name)
	fmt.Fprintf(commandHelp, "%s\t%s\n", Bold("SHORTNAME"), metadata.ShortName)
	fmt.Fprintf(commandHelp, "%s\t%s\n", Bold("USAGE"), metadata.Usage)
	fmt.Fprintf(commandHelp, "%s\n", Bold("FLAGS"))
	for n := 0; n < len(metadata.Flags); n++ {
		if flag, ok := metadata.Flags[n].(cli.StringFlag); ok {
			if flag.Name != "-u" && flag.Name != "-c" {
				fmt.Fprintf(commandHelp, "\t%s\t%s\n", flag.Name, flag.Usage)
			}
		}
	}
	tablemanagement.Println(commandHelp)
	tablemanagement.Flush()

}
Пример #12
0
func listSites(cmd *cobra.Command, args []string) error {
	c := plumbing.NewHTTPClient(nil)
	resp, err := c.Operations.ListSites(nil, auth.ClientCredentials())
	if err != nil {
		return err
	}

	sites := tm.NewTable(0, 10, 5, ' ', 0)
	fmt.Fprintf(sites, "SITE\tURL")
	for _, s := range resp.Payload {
		fmt.Fprintf(sites, "\n%s\t%s", s.Name, s.URL)
	}
	tm.Print(sites)
	tm.Flush()

	return nil
}
Пример #13
0
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()
	}
}
Пример #14
0
/* Run calls the Run function of CommandConfigs and verifies the response from that call.*/
func (versionsList VersionsList) Run(configs CommandConfigs) (bool, string) {
	resp := configs.Run()
	//if request did not fail
	if resp != nil {
		defer resp.Body.Close()
	} else {
		//exit the cli
		return true, ""
	}
	body, _ := ioutil.ReadAll(resp.Body)

	if resp.StatusCode == http.StatusOK {
		bodyString := string(body)
		var errorFormat formats.ErrorFormat
		err := json.Unmarshal([]byte(bodyString), &errorFormat)
		if err == nil {
			if errorFormat.ErrorCode == http.StatusUnauthorized {
				fmt.Println("Your session has expired.Please login and try again!")
				return false, configs.Cookie
			}
		} else {
			var appVersions []formats.AppVersion
			err := json.Unmarshal([]byte(bodyString), &appVersions)
			if err == nil {
				fmt.Println("\nApplication has ", len(appVersions[0].Versions), " versions. Details of versions are as follows.\n")
				for _, appVersion := range appVersions {
					versions := appVersion.Versions
					totals := tm.NewTable(0, 10, 5, ' ', 0)
					fmt.Fprintf(totals, "Version\tAutoDeploy\tStage\tRepoURL\n")
					fmt.Fprintf(totals, "-------\t---------\t-----\t-----------\n")

					for _, version := range versions {
						fmt.Fprintf(totals, "%s\t%s\t%s\t%s\n", version.Version, version.AutoDeployment, version.Stage, version.RepoURL)
					}
					tm.Println(totals)
					tm.Flush()
				}
			}
		}
	}
	return true, configs.Cookie
}
Пример #15
0
func (versionsList VersionsList) Run(c CommandConfigs) (bool, string) {
	var resp *http.Response
	var bodyStr string
	resp = c.Run()
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	if resp.Status == "200 OK" {

		bodyStr = string(body)
		var errorFormat formats.ErrorFormat
		err := json.Unmarshal([]byte(bodyStr), &errorFormat)

		if err == nil {
			//<TODO> Make these error checking functionality common
			if errorFormat.ErrorCode == http.StatusUnauthorized {
				fmt.Println("Your session has expired.Please login and try again!")
			}
		} else {
			var appVersions []formats.AppVersionFormat
			err := json.Unmarshal([]byte(bodyStr), &appVersions)
			if err == nil {
				fmt.Println("Application has ", len(appVersions[0].Versions), " versions. Details of versions are as follows.\n")
				for _, appVersion := range appVersions {
					versions := appVersion.Versions
					totals := tm.NewTable(0, 10, 5, ' ', 0)
					fmt.Fprintf(totals, "Version\tAutoDeploy\tStage\tRepoURL\n")
					fmt.Fprintf(totals, "-------\t---------\t-----\t-----------\n")

					for _, version := range versions {
						fmt.Fprintf(totals, "%s\t%s\t%s\t%s\n", version.Version, version.AutoDeployment, version.Stage, version.RepoURL)
					}
					tm.Println(totals)
					tm.Flush()
				}
			}

		}
	}
	return true, c.Cookie
}
Пример #16
0
func printJobs(lastApiResponse *healthd.ApiResponseJobs, status *healthdStatus) {
	goterm.Clear() // Clear current screen
	goterm.MoveCursor(1, 1)
	defer goterm.Flush()
	goterm.Println("Current Time:", status.FmtNow(), "   Status:", status.FmtStatus())

	if lastApiResponse == nil {
		goterm.Println("no data yet")
		return
	}

	columns := []string{
		"Job",
		//		"Jobs/Second", //minute? flag?
		"Total Count",
		"Success",
		"ValidationError",
		"Panic",
		"Error",
		"Junk",
		"Avg Response Time",
		"Stddev",
		"Min",
		"Max",
		"Total",
	}

	for i, s := range columns {
		columns[i] = goterm.Bold(goterm.Color(s, goterm.BLACK))
	}

	table := goterm.NewTable(0, goterm.Width()-1, 5, ' ', 0)
	fmt.Fprintf(table, "%s\n", strings.Join(columns, "\t"))

	for _, job := range lastApiResponse.Jobs {
		printJob(table, job)
	}

	goterm.Println(table)
}
Пример #17
0
/* Run calls the Run function of CommandConfigs and verifies the response from that call.*/
func (applist AppList) Run(configs CommandConfigs) (bool, string) {
	resp := configs.Run()
	//if request did not fail
	if resp != nil {
		defer resp.Body.Close()
	} else {
		//exit the cli
		return true, ""
	}
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode == http.StatusOK {
		bodyString := string(body)
		var errorFormat formats.ErrorFormat
		err := json.Unmarshal([]byte(bodyString), &errorFormat)
		if err == nil {
			if errorFormat.ErrorCode == http.StatusUnauthorized {
				fmt.Println(errorFormat.ErrorMessage)
				fmt.Println("Your session has expired.Please login and try again!")
				return false, configs.Cookie
			}
		} else {
			var apps []formats.App
			err := json.Unmarshal([]byte(bodyString), &apps)
			if err == nil {
				fmt.Println("\nYou have ", len(apps), " applications. Details of applications are as follows.\n")
				totals := tm.NewTable(0, 10, 5, ' ', 0)
				fmt.Fprintf(totals, "Name\tKey\tType\n")
				fmt.Fprintf(totals, "-------\t------\t-----\n")
				for _, app := range apps {
					fmt.Fprintf(totals, "%s\t%s\t%s\n", app.Name, app.Key, app.Type)
				}
				tm.Println(totals)
				tm.Flush()
			}
		}
	}
	return true, configs.Cookie
}
Пример #18
0
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()
	}
}
Пример #19
0
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!")
	}
}