Example #1
0
func (cmd *Command) overviewAction(backendId string, watch int, limit int) {
	var bk *engine.BackendKey
	if backendId != "" {
		bk = &engine.BackendKey{Id: backendId}
	}
	for {
		frontends, err := cmd.client.TopFrontends(bk, limit)
		if err != nil {
			cmd.printError(err)
			frontends = []engine.Frontend{}
		}

		servers, err := cmd.client.TopServers(bk, limit)
		if err != nil {
			cmd.printError(err)
			servers = []engine.Server{}
		}
		t := time.Now()
		if watch != 0 {
			goterm.Clear()
			goterm.MoveCursor(1, 1)
			goterm.Flush()
			fmt.Fprintf(cmd.out, "%s Every %d seconds. Top %d entries\n\n", t.Format("2006-01-02 15:04:05"), watch, limit)
		}
		cmd.printOverview(frontends, servers)
		if watch != 0 {
			goterm.Flush()
		} else {
			return
		}
		time.Sleep(time.Second * time.Duration(watch))
	}
}
Example #2
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
}
Example #3
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)
}
Example #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
}
Example #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
}
Example #6
0
// simple view. No in place updates
func RenderQuietView(progressChannel chan models.SyncProgress, wg *sync.WaitGroup) {
	depthChar := "--- "
	defer wg.Done()
	syncStates := make(map[string]map[string]string)
	for sp := range progressChannel {
		if _, exists := syncStates[sp.Node.Fqdn]; !exists {
			syncStates[sp.Node.Fqdn] = make(map[string]string)
		}
		switch sp.State {
		case "skipped":
			for i := 0; i < sp.Node.Depth; i++ {
				fmt.Printf(depthChar)
			}
			line := fmt.Sprintf("%v %v %v", sp.Node.Fqdn, sp.Repository, sp.State)
			tm.Printf(tm.Color(tm.Bold(line), tm.MAGENTA))
			tm.Flush()
		case "error":
			for i := 0; i < sp.Node.Depth; i++ {
				fmt.Printf(depthChar)
			}
			line := fmt.Sprintf("%v %v %v", sp.Node.Fqdn, sp.Repository, sp.State)
			tm.Printf(tm.Color(tm.Bold(line), tm.RED))
			tm.Flush()
		case "running":
			// only output state changes
			if syncStates[sp.Node.Fqdn][sp.Repository] != sp.State {
				for i := 0; i < sp.Node.Depth; i++ {
					fmt.Printf(depthChar)
				}
				line := fmt.Sprintf("%v %v %v", sp.Node.Fqdn, sp.Repository, sp.State)
				tm.Printf(tm.Color(line, tm.BLUE))
				tm.Flush()
			}
			syncStates[sp.Node.Fqdn][sp.Repository] = sp.State
		case "finished":
			for i := 0; i < sp.Node.Depth; i++ {
				fmt.Printf(depthChar)
			}
			line := fmt.Sprintf("%v %v %v", sp.Node.Fqdn, sp.Repository, sp.State)
			tm.Printf(tm.Color(tm.Bold(line), tm.GREEN))
			tm.Flush()
		}
	}
}
Example #7
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()
	}
}
Example #8
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()
}
Example #9
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()
}
Example #10
0
func main() {
	tm.Clear()
	tm.MoveCursor(0, 0)

	chart := tm.NewLineChart(100, 20)
	data := new(tm.DataTable)
	data.AddColumn("Time")
	data.AddColumn("Sin(x)")
	data.AddColumn("Cos(x+1)")

	for i := 0.1; i < 10; i += 0.1 {
		data.AddRow(i, math.Sin(i), math.Cos(i+1))
	}

	tm.Println(chart.Draw(data))
	tm.Flush()
}
Example #11
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
}
Example #12
0
func PrintImage(img image.Image) {
	width := goterm.Width()
	height := goterm.Height()
	img = resize.Resize(uint(width), uint(height), img, resize.NearestNeighbor)
	buf := ""
	for y := 0; y < height; y++ {
		buf += "\n"
		for x := 0; x < width; x++ {
			r, g, b, _ := img.At(x, y).RGBA()
			grayColor := color.Gray16{Y: uint16((r + g + b) / 3)}
			pixelColor := 232 + (grayColor.Y / 255 / 16)
			buf += fmt.Sprintf("\033[38;5;#%dm█\033[m", pixelColor)
		}
	}
	goterm.Print(buf)
	goterm.Flush()
}
Example #13
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()

}
Example #14
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()
	}
}
func main() {
	f, err := os.Create("box.txt")
	if err != nil {
		panic("Unable to create box file!")
	}
	defer f.Close()

	// Tell tm to use the file we just opened, not stdout
	tm.Output = bufio.NewWriter(f)

	// More or less stolen from the box example
	tm.Clear()
	box := tm.NewBox(30|tm.PCT, 20, 0)
	fmt.Fprint(box, "Some box content")
	tm.Print(tm.MoveTo(box.String(), 40|tm.PCT, 40|tm.PCT))
	tm.Flush()

	fmt.Println("Now view the contents of 'box.txt' in an ansi-capable terminal")
}
Example #16
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
}
Example #17
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
}
Example #18
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)
}
Example #19
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
}
Example #20
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!")
	}
}
Example #21
0
func Run(done chan bool) {

	if !verbose {
		tm.Clear() // Clear current screen
	}

	failed := false
	var failedUpdate builder.Update

	for {
		time.Sleep(time.Millisecond)
		if !verbose {
			tm.MoveCursor(1, 1)
			header := fmt.Sprintf("Building (%s)",
				nstime.NsReadable(time.Since(stated).Nanoseconds()),
			)
			termPrintln(header)
		}

		for worker, update := range statuses {
			if !verbose {
				tm.MoveCursor(worker+2, 1)
			}

			switch update.Status {
			case builder.Pending:
				termPrintln("[ IDLE ]")
			case builder.Started:
				ts := time.Since(update.TimeStamp)
				pbr := ">"

				s := fmt.Sprintf("%s %s (%s)",
					pbr,
					update.Target,
					nstime.NsReadable(ts.Nanoseconds()),
				)
				termPrintln(s)
			case builder.Fail:

				termPrintln("[ IDLE ]")
				exit = true
				failed = true
				failedUpdate = update
			case builder.Success:
				termPrintln("[ IDLE ]")
				break
			}

		}
		if !verbose {
			tm.Flush() // Call it every time at the end of rendering
		}
		if exit {
			if failed {
				if !verbose {
					tm.MoveCursor(worderCount+2, 1)
					failMessage(failedUpdate.Target)
					tm.Flush()
				} else {
					failMessage(failedUpdate.Target)
				}
			}
			done <- true
		}
	}
}
Example #22
0
func main() {
	var (
		errCh        = make(chan error, 16)
		receivedCh   = make(chan int, 1024)
		sentCh       = make(chan int, 1024)
		sent         = 0
		lastSent     = 0
		received     = 0
		lastReceived = 0
	)

	// read params (server address:port, qos settings, number of publishers, number of subscribers)
	flag.Parse()

	// generate topics in advance, so we can run the subscribers before starting to publish
	for i := 0; i < *numTop; i++ {
		newTopic()
	}

	//
	// subscribe to topics
	//

	// TODO: multiple subscribers.

	// initialise a timeout (if no messages are received in the given time since the last publish.)
	timeout := time.NewTimer(10 * time.Second)
	resetSubTimeout := func() {
		timeout.Reset(time.Duration(*subTimeout) * time.Second)
	}

	// discarding received messages
	messageHandler := func(client *mqtt.Client, m mqtt.Message) {
		if string(m.Payload()) == "hello world" {
			receivedCh <- 1
			resetSubTimeout() // reset timeout
		}
	}

	// prepare filter from topics and qos
	filters := map[string]byte{}
	for _, topic := range getTopics() {
		fmt.Printf("Created topic %s with qos %v\n", topic, *qos)
		filters[topic] = byte(*qos)
	}

	// multisubscribers
	fmt.Println("Connecting subscribers...")

	for i := 0; i < *numSub; i++ {
		subscriber := newClient()
		if token := subscriber.client.Connect(); token.Wait() && token.Error() != nil {
			errCh <- token.Error()
		}

		defer subscriber.client.Disconnect(250)

		token := subscriber.client.SubscribeMultiple(filters, messageHandler)
		if token.Wait() && token.Error() != nil {
			errCh <- token.Error()
		}

	}

	//
	// Publish to topics
	//

	// set value for timeout
	timeout = time.NewTimer(time.Duration(*subTimeout) * time.Second)

	go func() {
		for {
			select {
			case <-timeout.C:
				errCh <- fmt.Errorf("Subscriber timeout.. no more messages?")
			}
		}
	}()

	// publishers
	for i := 0; i < *numPub; i++ {
		go func() {
			c := newClient()
			if token := c.client.Connect(); token.Wait() && token.Error() != nil {
				errCh <- token.Error()
			}

			defer c.client.Disconnect(100)

			// publish (sequential per client)
			topics := getTopics()
			for k := 0; k < *numMessages; k++ {
				topic := topics[k%len(topics)]
				token := c.client.Publish(topic, byte(*qos), *retained, "hello world")
				if token.Wait() && token.Error() != nil {
					errCh <- token.Error()
				}
				sentCh <- 1
				time.Sleep(time.Duration(*pubDelay) * time.Millisecond)
			}
		}()
	}

	// creating fancy output
	// start := time.Now()
	redraw := time.NewTicker(100 * time.Millisecond)
	if *nograph {
		redraw = time.NewTicker(1 * time.Second)
	}
	row := 0.0

	// table
	data := new(tm.DataTable)
	data.AddColumn("Time (sec)")
	data.AddColumn("Sent")
	data.AddColumn("Received")

	for {
		select {
		case <-redraw.C:
			if !*nograph {
				tm.Clear()
				tm.Printf("[Published : Received]: [%v : %v]\n\n", sent, received)
				row += 1.0
				data.AddRow(row/10.0, float64(sent), float64(received))
				tm.Print(tm.NewLineChart(tm.Width()-4, tm.Height()-6).Draw(data))
				tm.Flush()
			} else {
				if sent != lastSent || received != lastReceived {
					fmt.Printf("[Published : Received]: [%v : %v]\n", sent, received)
					lastSent, lastReceived = sent, received
				}
			}

		case e := <-errCh:
			fmt.Println(e.Error())
			return
		case s := <-sentCh:
			sent += s
		case r := <-receivedCh:
			received += r
		}
	}
}
Example #23
0
func StatQueue(writeQ bool) error {

	var myresults results
	var wg sync.WaitGroup
	for id, sl := range record.RecordByThread {
		wg.Add(1)
		go func(tid string, rs []*record.Record) {

			defer wg.Done()

			for _, r := range rs {

				if !window.InCurrentWindow(r.Time) {
					continue
				}

				if len(r.Raw) < 151 {
					continue
				}
				txt := strings.Split(r.Raw[60:150], ">")
				if len(txt) < 2 {
					continue
				}
				tokens := strings.Split(txt[1], " ") // 60:140 to limit the scope of search, with reasonable margins
				if len(tokens) < 3 {
					continue
				}

				if writeQ {
					if ((tokens[1] == "Queue") && (tokens[2] == "command")) ||
						((tokens[1] == "Dequeue") && (tokens[2] == "and") && (tokens[3] == "execute")) {
						//2015/08/04 15:19:59.904847 magap302 masterag-11298 MDW INFO <SEI_MAAdminSequence.cpp#223 TID#13> Queue command 0x2aacbf979400 [Command#14015: kSEIBELibLoaded : BE->MAG:Notify the Master Agent that a lib has been loaded (version 1)^@] (from BENT0UCL4VXODY to masterag); Command sequence queue size: 0
						backToken := strings.Split(r.Raw[len(r.Raw)-40:len(r.Raw)], " ")
						last := len(backToken) - 1
						txt1 := strings.Join(backToken[last-2:last], " ")
						if txt1 == "queue size:" {
							if s, err := strconv.Atoi(backToken[last]); err == nil {
								myresults.Lock()
								myresults.HasRecords = append(myresults.HasRecords, &result{qSize: s, tid: tid, r: r})
								myresults.Unlock()
							}
						}
					}
				} else {
					if (tokens[1] == "Scheduling") && (tokens[3] == "command") && (tokens[6] == "Read-only") {
						//2015/12/03 05:07:12.577382 magap302 masterag-32357 MDW INFO <SEI_MAAdminSequence.cpp#196 TID#13> Scheduling the command in the Read-only command sequencer pool. Pool queue size: 393
						backToken := strings.Split(r.Raw[len(r.Raw)-40:len(r.Raw)], " ")
						last := len(backToken) - 1
						txt1 := strings.Join(backToken[last-2:last], " ")
						if txt1 == "queue size:" {
							if s, err := strconv.Atoi(backToken[last]); err == nil {
								myresults.Lock()
								myresults.HasRecords = append(myresults.HasRecords, &result{qSize: s, tid: tid, r: r})
								myresults.Unlock()
							}
						}
					}
				}
			}
		}(id, sl)
	}

	wg.Wait()
	sort.Sort(record.ByHasRecordTime{myresults.HasRecords})

	// Build chart
	chart := tm.NewLineChart(tm.Width()-10, tm.Height()-10)

	data := new(tm.DataTable)
	data.AddColumn("Seconds")
	data.AddColumn("QMax")
	data.AddColumn("QMin")

	type prec struct {
		max int
		min int
	}

	t0 := myresults.HasRecords[0].(*result).r.Time
	tmax := myresults.HasRecords[len(myresults.HasRecords)-1].(*result).r.Time
	indexMax := int(tmax.Sub(t0).Seconds())

	qmaxTime := time.Unix(0, 0)
	qmax := 0

	m := make(map[int]prec)
	for _, v := range myresults.HasRecords {
		r := v.(*result)
		d := int(r.r.Time.Sub(t0).Seconds())
		p, ok := m[d]
		if !ok {
			p = prec{r.qSize, r.qSize}
		} else {
			if p.max < r.qSize {
				p.max = r.qSize
			}
			if p.min > r.qSize {
				p.min = r.qSize
			}
		}
		m[d] = p

		if p.max > qmax {
			qmax = p.max
			qmaxTime = r.GetRecord().Time
		}
	}

	for t := 0; t <= int(indexMax); t++ {
		data.AddRow(float64(t), float64(m[t].max), float64(m[t].min))
	}

	tm.Println(chart.Draw(data))
	tm.Flush()

	fmt.Printf("Qmax=%d  at %s\n", qmax, qmaxTime.Format(utils.DateFormat))

	return nil
}
Example #24
0
//Display the distribution for a given command
func StatCmdDistribution(cmdName string) {

	for _, ss := range buildStats() {
		if ss.cmd == cmdName {
			// Build chart
			chart := tm.NewLineChart(tm.Width()-10, tm.Height()-33)

			data := new(tm.DataTable)
			data.AddColumn("CmdCount")
			data.AddColumn("Duration")

			for i, rec := range ss.records {
				if d, err := rec.GetCmdDuration(); err != nil {
					data.AddRow(float64(i), -1.)
				} else {
					data.AddRow(float64(i), float64(d.Nanoseconds()/1000000))
				}
			}

			tm.Println(chart.Draw(data))
			tm.Flush()

			// Statistics for that particular command
			{
				w := new(tabwriter.Writer)
				w.Init(os.Stdout, 20, 0, 2, ' ', tabwriter.AlignRight)

				fmt.Fprintln(w, "Command\tcount\tmiss\tmin (ms)\tmax (ms)\tavg (ms)\t95% (ms)\t")
				c := int64(len(ss.records) - ss.incomplete)
				i95 := c * 95 / 100

				if c == 0 {
					c = 1
				}
				percentile95 := int64(-1)
				if d95, err := ss.records[i95].GetCmdDuration(); err == nil {
					percentile95 = d95.Nanoseconds()
				}

				fmt.Fprintf(w, "%s\t%d\t%d\t%d\t%d\t%d\t%d\t\n", ss.cmd, len(ss.records), ss.incomplete, ss.min.Nanoseconds()/1000000, ss.max.Nanoseconds()/1000000, ss.sum.Nanoseconds()/1000000/c, percentile95/1000000)

				fmt.Fprintln(w)
				w.Flush()

			}
			// The 10 slowest occurence
			{
				w := new(tabwriter.Writer)
				w.Init(os.Stdout, 5, 0, 2, ' ', tabwriter.TabIndent)
				fmt.Fprintln(w, "Duration(ms)\tcmd\t")

				min := 10
				if len(ss.records) < 10 {
					min = len(ss.records)
				}
				for i := 1; i <= min; i++ {
					rec := ss.records[len(ss.records)-i]
					if d, err := rec.GetCmdDuration(); err != nil {
						fmt.Fprintf(w, "-\t%s\t\n", rec.Raw)
					} else {
						fmt.Fprintf(w, "%d\t%s\t\n", d.Nanoseconds()/1000000, rec.Raw)
					}

				}

				fmt.Fprintln(w)
				w.Flush()
			}
			return
		}
	}

}
Example #25
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()
	}
}