Beispiel #1
0
func (a *AppEnv) GetEnvs(cli plugin.CliConnection, args []string) ([]string, error) {
	if loggedIn, _ := cli.IsLoggedIn(); loggedIn == false {
		return nil, errors.New("You must login first!")
	}

	if len(args) <= 1 {
		return nil, errors.New("You must specify an app name")
	}

	cliOut, err := a.GetAppEnvFromCli(cli, args[1])

	vcapServicesExport := a.GetJsonAndFormat("VCAP_SERVICES", cliOut)
	vcapAppExport := a.GetJsonAndFormat("VCAP_APPLICATION", cliOut)

	envvars := []string{}

	if vcapServicesExport != "" {
		envvars = append(envvars, vcapServicesExport)
	}

	if vcapAppExport != "" {
		envvars = append(envvars, vcapAppExport)
	}

	return envvars, err
}
func startedApps(cliConnection plugin.CliConnection, url string) ([]StartedApp, error) {
	appsJson, err := cliConnection.CliCommandWithoutTerminalOutput("curl", url)
	if nil != err {
		return nil, err
	}
	data := strings.Join(appsJson, "\n")
	var appsData map[string]interface{}
	json.Unmarshal([]byte(data), &appsData)

	apps := []StartedApp{}
	for _, app := range appsData["resources"].([]interface{}) {
		entity := app.(map[string]interface{})["entity"].(map[string]interface{})
		state := entity["state"].(string)
		if state == "STARTED" {
			metadata := app.(map[string]interface{})["metadata"].(map[string]interface{})
			result := StartedApp{
				Name:     entity["name"].(string),
				Guid:     metadata["guid"].(string),
				SpaceUrl: entity["space_url"].(string),
				State:    state,
			}
			apps = append(apps, result)
		}
	}

	if nil != appsData["next_url"] {
		next, _ := startedApps(cliConnection, appsData["next_url"].(string))
		apps = append(apps, next...)
	}

	return apps, err
}
Beispiel #3
0
func (c *NozzlerCmd) Run(cliConnection plugin.CliConnection, args []string) {
	var debug bool
	if args[0] != "nozzle" {
		return
	}
	c.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())

	fc := flags.NewFlagContext(setupFlags())
	err := fc.Parse(args[1:]...)
	if err != nil {
		c.ui.Failed(err.Error())
	}
	if fc.IsSet("debug") {
		debug = fc.Bool("debug")
	}

	dopplerEndpoint, err := cliConnection.DopplerEndpoint()
	if err != nil {
		c.ui.Failed(err.Error())
	}

	authToken, err := cliConnection.AccessToken()
	if err != nil {
		c.ui.Failed(err.Error())
	}

	client := firehose.NewClient(authToken, dopplerEndpoint, debug, c.ui)
	client.Start()
}
Beispiel #4
0
func (plugin OpenPlugin) runServiceOpen(cliConnection plugin.CliConnection, args []string) {
	output, err := cliConnection.CliCommandWithoutTerminalOutput("service", args[1], "--guid")
	if err != nil {
		fmt.Fprintln(os.Stdout, "error: service does not exist")
		os.Exit(1)
	}
	serviceInstanceGUID := strings.TrimSpace(output[0])

	output, err = cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("/v2/service_instances/%s", serviceInstanceGUID))
	if err != nil {
		fmt.Fprintln(os.Stdout, "error: service does not exist")
		os.Exit(1)
	}
	jsonStr := ""
	for _, line := range output {
		jsonStr += line + "\n"
	}

	response := serviceInstanceResponse{}
	json.Unmarshal([]byte(jsonStr), &response)

	url := response.Entity.DashboardURL
	if url == "" {
		fmt.Println("No dashboard available")
	} else {
		open.Run(url)
	}
}
Beispiel #5
0
func Curl(cli plugin.CliConnection, result interface{}, args ...string) error {
	output, err := cli.CliCommandWithoutTerminalOutput(append([]string{"curl"}, args...)...)
	if err != nil {
		return err
	}

	buf := []byte(strings.Join(output, "\n"))

	var errorResponse curlError
	err = json.Unmarshal(buf, &errorResponse)
	if err != nil {
		return err
	}

	if errorResponse.Code != 0 {
		return errors.New(errorResponse.Description)
	}

	if result != nil {
		err = json.Unmarshal(buf, result)
		if err != nil {
			return err
		}
	}

	return nil
}
Beispiel #6
0
func (s *FirehoseStatsCmd) Run(cliConnection plugin.CliConnection, args []string) {

	if args[0] != "firehose-stats" {
		return
	}

	s.cfUI = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())

	dopplerEndpoint, err := cliConnection.DopplerEndpoint()
	if err != nil {
		s.cfUI.Failed(err.Error())
	}

	authToken, err := cliConnection.AccessToken()
	if err != nil {
		s.cfUI.Failed(err.Error())
	}
	firehoseChan := make(chan *events.Envelope)
	client := firehose.NewClient(authToken, dopplerEndpoint, s.cfUI, firehoseChan)
	client.Start()

	statsUI := stats.New(client, s.cfUI, cliConnection)
	statsUI.Start()

}
func getAppGuid(cliConnection plugin.CliConnection, appName string) string {
	repo := core_config.NewRepositoryFromFilepath(config_helpers.DefaultFilePath(), func(err error) {
		if err != nil {
			fmt.Println("\nERROR:", err)
			os.Exit(1)
		}
	})
	spaceGuid := repo.SpaceFields().Guid

	cmd := []string{"curl", fmt.Sprintf("/v2/spaces/%v/apps?q=name:%v&inline-relations-depth=1", spaceGuid, appName)}
	output, err := cliConnection.CliCommandWithoutTerminalOutput(cmd...)
	if err != nil {
		for _, e := range output {
			fmt.Println(e)
		}
		os.Exit(1)
	}

	search := &Search{}
	if err := json.Unmarshal([]byte(strings.Join(output, "")), &search); err != nil {
		fmt.Println("\nERROR:", err)
		os.Exit(1)
	}

	return search.Resources[0].Metadata.Guid
}
func (c *DemoCmd) Run(cliConnection plugin.CliConnection, args []string) {
	switch args[0] {
	case "list-apps":
		fc, err := parseArguments(args)
		if err != nil {
			exit1(err.Error())
		}

		endpoint, err := cliConnection.ApiEndpoint()
		if err != nil {
			exit1("Error getting targeted endpoint: " + err.Error())
		}
		fmt.Printf("Listing apps @ endpoint %s/v2/apps...\n\n", endpoint)

		allApps, err := getAllApps(cliConnection)
		if err != nil {
			exit1("Error curling v2/apps: " + err.Error())
		}

		for _, app := range allApps.Resources {
			if (fc.IsSet("started") && app.Entity.State == "STARTED") ||
				(fc.IsSet("stopped") && app.Entity.State == "STOPPED") ||
				(!fc.IsSet("stopped") && !fc.IsSet("started")) {
				fmt.Println(app.Entity.Name)
			}
		}

	case "CLI-MESSAGE-UNINSTALL":
		fmt.Println("Thanks for using this demo")
	}
}
Beispiel #9
0
// CheckUpApps performs checkup on applications and adds the result to triage map
func (c *DoctorPlugin) CheckUpApps(cliConnection plugin.CliConnection, triage []string, listOfRunningApps []plugin_models.GetAppsModel, listOfStoppedApps []plugin_models.GetAppsModel) []string {
	const alarmCPU float64 = 85.0

	for _, i := range listOfRunningApps {
		app, err := cliConnection.GetApp(i.Name)
		if err != nil {
			c.ui.Failed(err.Error())
		}

		if len(app.StagingFailedReason) > 0 {
			triage = append(triage, i.Name+" ___ StagingFailedReason: "+app.StagingFailedReason)
		}

		insts := app.Instances

		for _, ins := range insts {
			if ins.CpuUsage > alarmCPU {
				triage = append(triage, i.Name+" ___ CPU usage over %85 percent!")
			}

			if float64(ins.DiskUsage) > float64(ins.DiskQuota)*0.80 {
				triage = append(triage, i.Name+" ___ DiskUsage over %80 percent of DiskQuota")
			}

			if float64(ins.MemUsage) > float64(ins.MemQuota)*0.80 {
				triage = append(triage, i.Name+" ___ MemUsage over %80 percent of MemQuota")
			}

			if float64(ins.MemUsage) < float64(ins.MemQuota)*0.15 {
				triage = append(triage, i.Name+" ___ MemUsage lower than %15 percent of MemQuota, scaledown is an option.")
			}

			if len(insts) > 1 && float64(ins.MemUsage) < float64(ins.MemQuota)*0.15 && ins.CpuUsage < 10.0 {
				triage = append(triage, i.Name+" ___ app has more than one instance running with very low resource consumption. candidate for scaling down.")
			}

		}

		routes := app.Routes

		if len(routes) == 0 {
			triage = append(triage, i.Name+" ___ You have a running application that does not have a route!")
		}
	}

	for _, y := range listOfStoppedApps {
		app, err := cliConnection.GetApp(y.Name)
		if err != nil {
			c.ui.Failed(err.Error())
		}

		if len(app.StagingFailedReason) > 0 {
			triage = append(triage, y.Name+" ___ StagingFailedReason: "+app.StagingFailedReason)
		}
	}

	return triage

}
func GetAllApps(cliConnection plugin.CliConnection) ([]AppModel, error) {
	response, err := cliConnection.CliCommandWithoutTerminalOutput("curl", "v2/apps")

	apps := AppsModel{}
	err = json.Unmarshal([]byte(response[0]), &apps)

	return apps.Resources, err
}
func UnmapContextRoute(cliConnection plugin.CliConnection, args []string) {
	app := args[1]
	domain := args[2]
	host := args[3]
	path := args[4]

	mySpace, _ := cliConnection.GetCurrentSpace()

	output, err := cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("v2/apps?q=name:%s&q=space_guid:%s", app, mySpace.Guid))
	FreakOut(err)
	apps := AppsModel{}
	err = json.Unmarshal([]byte(output[0]), &apps)
	FreakOut(err)
	if len(apps.Resources) == 0 {
		fmt.Printf("App %s not found", app)
		return
	}
	appGuid := apps.Resources[0].Metadata.Guid

	output, err = cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("v2/domains?q=name:%s", domain))
	FreakOut(err)
	domains := DomainsModel{}
	err = json.Unmarshal([]byte(output[0]), &domains)
	FreakOut(err)
	if len(domains.Resources) == 0 {
		fmt.Printf("Domain %s not found", domain)
		return
	}
	domainGuid := domains.Resources[0].Metadata.Guid

	output, err = cliConnection.CliCommandWithoutTerminalOutput("curl",
		fmt.Sprintf("v2/routes?q=domain_guid:%s&q=host:%s&q=path:%s", domainGuid, host, path))
	FreakOut(err)
	routes := RoutesModel{}
	err = json.Unmarshal([]byte(output[0]), &routes)
	FreakOut(err)
	if len(routes.Resources) == 0 {
		fmt.Printf("Route not found host: %s, path: %s", host, path)
		return
	}
	routeGuid := routes.Resources[0].Metadata.Guid

	output, err = cliConnection.CliCommandWithoutTerminalOutput("curl",
		fmt.Sprintf("v2/apps/%s/routes/%s", appGuid, routeGuid), "-X", "DELETE")
	FreakOut(err)
	mappedApp := AppModel{}
	err = json.Unmarshal([]byte(output[0]), &mappedApp)
	FreakOut(err)
	if mappedApp.Metadata.Guid == "" {
		error := ErrorModel{}
		err = json.Unmarshal([]byte(output[0]), &error)
		FreakOut(err)
		fmt.Printf("Failed to map route: %s", error.Description)
		return
	}

	fmt.Printf("Route successfully unmapped.")
}
Beispiel #12
0
// Curl calls cf curl  and return the resulting json. This method will panic if
// the api is depricated
func Curl(cli plugin.CliConnection, path string) (map[string]interface{}, error) {
	output, err := cli.CliCommandWithoutTerminalOutput("curl", path)

	if nil != err {
		return nil, err
	}

	return parseOutput(output)
}
func (app *AppStatus) scaleUp(cliConnection plugin.CliConnection) {
	// If not already started, start it
	if app.state != "started" {
		cliConnection.CliCommandWithoutTerminalOutput("start", app.name)
		app.state = "started"
	}
	app.countRequested++
	cliConnection.CliCommandWithoutTerminalOutput("scale", "-i", strconv.Itoa(app.countRequested), app.name)
}
Beispiel #14
0
func setServiceCreds(conn plugin.CliConnection, name string, creds map[string]interface{}) error {
	marshaled, err := json.Marshal(creds)
	if err != nil {
		return err
	}

	_, err = conn.CliCommandWithoutTerminalOutput("uups", name, "-p", string(marshaled[:]))
	return err
}
Beispiel #15
0
func (plugin ConsolePlugin) KillInstanceZero(cliConnection plugin.CliConnection, appGuid string) {

	plugin.Log("Killing instance 0.\n", false)

	// Kill the first instance and wait for it to come back up
	appURL := fmt.Sprintf("/v2/apps/%v/instances/0", appGuid)
	cmd := []string{"curl", appURL, "-X", "DELETE"}

	cliConnection.CliCommandWithoutTerminalOutput(cmd...)
}
Beispiel #16
0
func (plugin ConsolePlugin) ChangeInstanceCount(cliConnection plugin.CliConnection, appGuid string, instances int) {

	plugin.Log(fmt.Sprintf("Changing instance count to %v.\n", instances), false)

	appURL := fmt.Sprintf("/v2/apps/%v", appGuid)
	newCommand := fmt.Sprintf("{\"instances\":%v}", instances)
	cmd := []string{"curl", appURL, "-X", "PUT", "-d", newCommand}

	cliConnection.CliCommandWithoutTerminalOutput(cmd...)
}
func (app *AppStatus) scaleDown(cliConnection plugin.CliConnection) {
	app.countRequested--
	// If going to zero, stop the app
	if app.countRequested == 0 {
		cliConnection.CliCommandWithoutTerminalOutput("stop", app.name)
		app.state = "stopped"
	} else {
		cliConnection.CliCommandWithoutTerminalOutput("scale", "-i", strconv.Itoa(app.countRequested), app.name)
	}
}
Beispiel #18
0
func createServices(cliConnection plugin.CliConnection) {
	services, err := cliConnection.GetServices()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	redisFound, redisBound, sqlFound, sqlBound := false, false, false, false
	for _, service := range services {
		if service.Name == "hackday-rediscloud" {
			redisFound = true
			for _, app := range service.ApplicationNames {
				if app == "hackday-nc" {
					redisBound = true
				}
			}
		}
		if service.Name == "hackday-cleardb" {
			sqlFound = true
			for _, app := range service.ApplicationNames {
				if app == "hackday-nc" {
					sqlBound = true
				}
			}
		}
	}
	if !redisFound {
		_, err = cliConnection.CliCommand("cs", "rediscloud", "30mb", "hackday-rediscloud")
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}
	if !redisBound {
		_, err = cliConnection.CliCommand("bs", "hackday-nc", "hackday-rediscloud")
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}
	if !sqlFound {
		_, err = cliConnection.CliCommand("cs", "cleardb", "turtle", "hackday-cleardb")
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}
	if !sqlBound {
		_, err = cliConnection.CliCommand("bs", "hackday-nc", "hackday-cleardb")
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}
}
Beispiel #19
0
func (c *CopyEnv) RetrieveAppNameEnv(cliConnection plugin.CliConnection, app_name string) ([]string, error) {
	output, err := cliConnection.CliCommandWithoutTerminalOutput("env", app_name)

	if err != nil {
		for _, val := range output {
			fmt.Println(val)
		}
	}

	return output, err
}
Beispiel #20
0
func organizationName(cliConnection plugin.CliConnection, org_url string) (string, error) {
	output, error := cliConnection.CliCommandWithoutTerminalOutput("curl", org_url)
	if error != nil {
		return "", error
	}
	data := strings.Join(output, "\n")
	var org map[string]interface{}
	json.Unmarshal([]byte(data), &org)
	entity := org["entity"].(map[string]interface{})
	return entity["name"].(string), error
}
func (cmd *Wildcard) getMatchedApps(cliConnection plugin.CliConnection, args []string) []plugin_models.ApplicationSummary {
	pattern := args[1]
	output, _ := cliConnection.GetApps()
	for i := 0; i < (len(output)); i++ {
		ok, _ := filepath.Match(pattern, output[i].Name)
		if ok {
			cmd.matchedApps = append(cmd.matchedApps, output[i])
		}
	}
	return cmd.matchedApps
}
Beispiel #22
0
func checkArgs(cliConnection plugin.CliConnection, args []string) error {
	if len(args) < 2 {
		if args[0] == "open" {
			cliConnection.CliCommand(args[0], "-h")
			return errors.New("Appname is needed")
		} else if args[0] == "service-open" {
			cliConnection.CliCommand(args[0], "-h")
			return errors.New("Appname is needed")
		}
	}
	return nil
}
Beispiel #23
0
func getServiceApp(conn plugin.CliConnection, name string) (string, error) {
	services, err := conn.GetServices()
	if err != nil {
		return "", err
	}
	for _, service := range services {
		if service.Name == name {
			return service.ApplicationNames[0], nil
		}
	}
	return "", errors.New(fmt.Sprintf("No service %s bound to an app", name))
}
func GetAppsInOneOrg(cliConnection plugin.CliConnection, orgName string) ([]plugin_models.GetAppsModel, error) {
	_, err := cliConnection.CliCommandWithoutTerminalOutput("target", "-o", orgName)
	if err != nil {
		return []plugin_models.GetAppsModel{}, errors.New("Failed to target org '" + orgName + "'")
	}

	apps, err := cliConnection.GetApps()
	if err != nil {
		return []plugin_models.GetAppsModel{}, errors.New("Failed to get apps in organization '" + orgName + "'")
	}

	return apps, nil
}
Beispiel #25
0
func (plugin ConsolePlugin) ChangeAppCommand(cliConnection plugin.CliConnection, appGuid string, startCmd string) {
	plugin.Log(fmt.Sprintf("Updating app start command to '%v'.\n", startCmd), false)

	startCmd = strings.Replace(startCmd, "\"", "\\\"", -1)

	appURL := fmt.Sprintf("/v2/apps/%v", appGuid)
	newCommand := fmt.Sprintf("{\"command\":\"%v\"}", startCmd)

	cmd := []string{"curl", appURL, "-X", "PUT", "-d", newCommand}

	cliConnection.CliCommandWithoutTerminalOutput(cmd...)

}
Beispiel #26
0
func callAndValidateCLI(cli plugin.CliConnection, path string) ([]string, error) {
	output, err := cli.CliCommandWithoutTerminalOutput("curl", path)

	if nil != err {
		return nil, err
	}

	if nil == output || 0 == len(output) {
		return nil, errors.New("CF API returned no output")
	}

	return output, nil
}
func getMatchedApps(cliConnection plugin.CliConnection, args string) []plugin_models.GetAppsModel {
	pattern := args
	output, err := cliConnection.GetApps()
	checkError(err)
	matchedApps := []plugin_models.GetAppsModel{}
	for i := 0; i < len(output); i++ {
		ok, _ := filepath.Match(pattern, output[i].Name)
		if ok {
			matchedApps = append(matchedApps, output[i])
		}
	}
	return matchedApps
}
func (cmd *Wildcard) WildcardCommand(cliConnection plugin.CliConnection, args []string) {
	force := false
	if args[0] == "-f" {
		force = true
		args = append(args[:0], args[1:]...)
	}
	command := args[0]
	pattern := args[1]
	apps := getMatchedApps(cliConnection, pattern)
	if !force && len(apps) > 0 {
		cmd.WildcardCommandApps(cliConnection, pattern)
		fmt.Println("")
		fmt.Printf("Would you like to %s (%s)nteractively, (%s)ll, or (%s)ancel ?%s", command, table.PromptColor("i"), table.PromptColor("a"), table.PromptColor("c"), table.PromptColor(">"))
		var mode string
		fmt.Scanf("%s", &mode)
		if strings.EqualFold(mode, "a") || strings.EqualFold(mode, "all") {
			force = true
		} else if strings.EqualFold(mode, "i") || strings.EqualFold(mode, "interactively") {
			force = false
		} else {
			fmt.Println(table.WarningColor("Cancelled"))
			return
		}
	} else {
		introduction(cliConnection, pattern)
	}
	for _, app := range apps {
		coloredCommand := table.EntityNameColor(command)
		coloredAppName := table.EntityNameColor(app.Name)
		if !force {
			var confirmation string
			fmt.Printf("Really %s app %s?%s ", table.PromptColor(command), table.PromptColor(app.Name), table.PromptColor(">"))
			fmt.Scanf("%s", &confirmation)
			if !strings.EqualFold(confirmation, "y") && !strings.EqualFold(confirmation, "yes") {
				continue
			}
		}
		fmt.Println("Running command", coloredCommand, "on app", coloredAppName)
		args[1] = app.Name
		fmt.Println(args)
		_, err := cliConnection.CliCommand(args...)
		if err != nil {
			fmt.Println("PLUGIN ERROR: Error from CliCommand: ", err)
		}
	}
	if len(apps) == 0 {
		fmt.Println(table.WarningColor("No apps found matching"), table.WarningColor(pattern))
	} else {
		fmt.Println(table.SuccessColor("OK"))
	}
}
func scaleApp(cliConnection plugin.CliConnection, appName string, instances int) {
	// lock mutex, to avoid colliding with other cli commands
	commandLock.Lock()
	defer commandLock.Unlock()

	term.ScaleApp(appName, instances)

	cmd := []string{"scale", appName, "-i", fmt.Sprintf("%d", instances)}
	if _, err := cliConnection.CliCommandWithoutTerminalOutput(cmd...); err != nil {
		term.Close()
		fmt.Println("\nERROR:", err)
		os.Exit(0)
	}
}
Beispiel #30
0
// AppsStateStopped will return a list of app whose state is running
func (c *DoctorPlugin) AppsStateStopped(cliConnection plugin.CliConnection) []plugin_models.GetAppsModel {
	var res []plugin_models.GetAppsModel
	appsListing, err := cliConnection.GetApps()
	if err != nil {
		c.ui.Failed(err.Error())
	}

	for _, app := range appsListing {
		if app.State == "stopped" {
			res = append(res, app)
		}
	}
	return res
}