Esempio n. 1
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
}
Esempio n. 2
0
func (c *AppLister) Run(cliConnection plugin.CliConnection, args []string) {
	orgs, err := cliConnection.GetOrgs()
	if err != nil {
		fmt.Println("Error getting orgs:", err)
		os.Exit(1)
	}

	for _, org := range orgs {
		_, err := cliConnection.CliCommandWithoutTerminalOutput("t", "-o", org.Name)
		if err != nil {
			fmt.Println("Error targeting org: ", org.Name)
			os.Exit(1)
		}

		apps, err := cliConnection.GetApps()
		if err != nil {
			fmt.Println("Error getting applications from org: ", org.Name)
			os.Exit(1)
		}

		for _, app := range apps {
			fmt.Println(app.Name)
		}
	}
}
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
}
Esempio n. 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)
	}
}
Esempio n. 5
0
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
}
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
}
Esempio n. 7
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)
}
Esempio n. 9
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
}
Esempio n. 10
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...)
}
Esempio n. 11
0
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)
	}
}
Esempio n. 12
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...)
}
Esempio n. 13
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
}
Esempio n. 14
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
}
Esempio n. 15
0
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
}
Esempio n. 16
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
}
Esempio n. 17
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...)

}
Esempio n. 18
0
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)
	}
}
Esempio n. 19
0
func (plugin OpenPlugin) runAppOpen(cliConnection plugin.CliConnection, args []string) {
	output, err := cliConnection.CliCommandWithoutTerminalOutput("app", args[1])
	if err != nil {
		fmt.Fprintln(os.Stdout, "error: app does not exist")
		os.Exit(1)
	}
	url, err := getUrlFromOutput(output)
	if err != nil {
		fmt.Fprintln(os.Stdout, "error: ", err)
		os.Exit(1)
	}

	open.Run(multiRoutesMenu(os.Stdin, url))

}
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.")
}
Esempio n. 21
0
func (plugin ConsolePlugin) GetLatestLogDate(cliConnection plugin.CliConnection, appName string) string {

	plugin.Log("Checking app log datestamps.\n", false)

	// Regex for tmate log line
	re := regexp.MustCompile(`(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{2}-\d{4})\s`)

	// Find last log entry
	cmd := []string{"logs", appName, "--recent"}

	output, _ := cliConnection.CliCommandWithoutTerminalOutput(cmd...)
	lastLine := output[len(output)-1]

	matches := re.FindStringSubmatch(lastLine)
	return matches[0]
}
Esempio n. 22
0
func (c *FastPushPlugin) GetApiEndpoint(cliConnection plugin.CliConnection, appName string) string {
	results, err := cliConnection.CliCommandWithoutTerminalOutput("app", appName)
	if err != nil {
		c.ui.Failed(err.Error())
	}

	for _, line := range results {
		match, _ := regexp.MatchString("^urls:.*", line)
		if match {
			parts := strings.Fields(line)
			if len(parts) > 1 {
				return "https://" + parts[1] + "/_fastpush"
			}
		}
	}
	panic("Could not find usable route for this app. Make sure at least one route is mapped to this app")
}
Esempio n. 23
0
func (plugin ConsolePlugin) FindAppGuid(cliConnection plugin.CliConnection, appName string) (string, AppSearchEntity) {

	plugin.Log(fmt.Sprintf("Finding app guid for %v ... ", appName), false)

	confRepo := core_config.NewRepositoryFromFilepath(config_helpers.DefaultFilePath(), fatalIf)
	spaceGuid := confRepo.SpaceFields().Guid

	appQuery := fmt.Sprintf("/v2/spaces/%v/apps?q=name:%v&inline-relations-depth=1", spaceGuid, appName)
	cmd := []string{"curl", appQuery}

	output, _ := cliConnection.CliCommandWithoutTerminalOutput(cmd...)
	res := &AppSearchResults{}
	json.Unmarshal([]byte(strings.Join(output, "")), &res)

	plugin.Log(fmt.Sprintf("%v \n", res.Resources[0].Metadata.Guid), true)

	return res.Resources[0].Metadata.Guid, res.Resources[0].Entity
}
Esempio n. 24
0
func (plugin ConsolePlugin) WaitAndConnect(cliConnection plugin.CliConnection, appName string, instances int, lastDate string) {

	plugin.Log("Waiting for SSH endpoint.\n", false)

	// Regex for tmate log line
	exp := fmt.Sprintf("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{2}-\\d{4}\\s\\[App\\/%v\\]\\s{3}[^\\n]+\\s([^\\s]+\\@[a-z]+\\.tmate\\.io)", instances-1)
	reDate := regexp.MustCompile(`(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{2}-\d{4})\s`)

	re := regexp.MustCompile(exp)

	// Wait until new ssh endpoint turns up
	cmd := []string{"logs", appName, "--recent"}

	var ssh_endpoint string

	for ssh_endpoint == "" {
		output, _ := cliConnection.CliCommandWithoutTerminalOutput(cmd...)

		for _, v := range output {
			matches := re.FindAllStringSubmatch(v, -1)
			lineDate := reDate.FindStringSubmatch(v)

			if lineDate != nil {
				for _, m := range matches {
					if lineDate[0] > lastDate {
						ssh_endpoint = m[1]
					}
				}
			}

		}
	}

	plugin.Log(fmt.Sprintf("SSHing to %v\n", ssh_endpoint), false)

	// Launch SSH
	ps := exec.Command("ssh", ssh_endpoint)
	ps.Stdout = os.Stdout
	ps.Stderr = os.Stderr
	ps.Stdin = os.Stdin

	ps.Run()
}
Esempio n. 25
0
// CheckUpRoutes performs checkup on currently defined routes in cloudfoundry
func (c *DoctorPlugin) CheckUpRoutes(cliConnection plugin.CliConnection, triageRoutes []string) []string {
	results, err := cliConnection.CliCommandWithoutTerminalOutput("routes")
	if err != nil {
		c.ui.Failed(err.Error())
	}

	for _, line := range results {
		// regex to match cf routes output and see if there are unbound routes
		match, _ := regexp.MatchString("^[a-zA-Z]*\\s*\\S*\\s*\\S*\\s*", line)
		if match {
			parts := strings.Fields(line)

			if len(parts) == 3 {
				triageRoutes = append(triageRoutes, "Host: "+parts[1]+" <--->  Domain: "+parts[2])
			}
		}

	}
	return triageRoutes
}
Esempio n. 26
0
func (c *FastPushPlugin) GetAppVersionId(cliConnection plugin.CliConnection, appName string) string {
	results, err := cliConnection.CliCommandWithoutTerminalOutput("env", appName)
	if err != nil {
		c.ui.Failed(err.Error())
	}

	var vcap VCAPApplication

	for _, line := range results {
		if strings.HasPrefix(line, "{\n \"VCAP_APPLICATION\"") {
			data := []byte(line)
			if err := json.Unmarshal(data, &vcap); err != nil {
				panic(err)
			} else {
				return vcap.VCAP_APPLICATION.ApplicationID + "-" + vcap.VCAP_APPLICATION.ApplicationVersion
			}
		}
	}

	panic("Could not find usable VCAP_APPLICATION block")
}
func (cmd *DiegoMigrationCmd) cfcurl(cli plugin.CliConnection, cliCommandArgs ...string) (data []byte, err error) {
	cliCommandArgs = append([]string{"curl"}, cliCommandArgs...)

	output, err := cli.CliCommandWithoutTerminalOutput(cliCommandArgs...)

	if nil != err {
		return nil, err
	}

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

	response := strings.Join(output, " ")

	if 0 == len(response) || "" == response {
		return nil, errors.New("Failed to join output")
	}

	return []byte(response), err
}
Esempio n. 28
0
func (cmd *Wildcard) WildcardCommandDelete(cliConnection plugin.CliConnection, args string, force *bool, routes *bool) {
	output := getMatchedApps(cliConnection, args)
	exit := false
	if !*force && len(output) > 0 {
		cmd.WildcardCommandApps(cliConnection, args)
		fmt.Println("")
		fmt.Printf("Would you like to delete the apps (%s)nteractively, (%s)ll, or (%s)ancel this command?%s", 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") {
		} else {
			fmt.Println(table.WarningColor("Delete cancelled"))
			exit = true
		}
	} else {
		introduction(cliConnection, args)
	}
	if !exit {
		for _, app := range output {
			coloredAppName := table.EntityNameColor(app.Name)
			if *force && *routes {
				cliConnection.CliCommandWithoutTerminalOutput("delete", app.Name, "-f", "-r")
				fmt.Println("Deleting app", coloredAppName, "and its mapped routes")
			} else if *force {
				cliConnection.CliCommandWithoutTerminalOutput("delete", app.Name, "-f")
				fmt.Println("Deleting app", coloredAppName)
			} else {
				var confirmation string
				fmt.Printf("Really delete the app %s?%s ", table.PromptColor(app.Name), table.PromptColor(">"))
				fmt.Scanf("%s", &confirmation)
				if strings.EqualFold(confirmation, "y") || strings.EqualFold(confirmation, "yes") {
					if *routes {
						cliConnection.CliCommandWithoutTerminalOutput("delete", app.Name, "-f", "-r")
						fmt.Println("Deleting app", coloredAppName, "and its mapped routes")
					} else {
						cliConnection.CliCommandWithoutTerminalOutput("delete", app.Name, "-f")
						fmt.Println("Deleting app", coloredAppName)
					}
				}
			}
		}
	}
	if len(output) == 0 {
		fmt.Println(table.WarningColor("No apps found matching"), table.WarningColor(args))
	} else {
		fmt.Println(table.SuccessColor("OK"))
	}
}
func DeleteContextRoute(cliConnection plugin.CliConnection, args []string) {
	domain := args[1]
	host := args[2]
	path := args[3]

	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/routes/%s", routeGuid), "-X", "DELETE")
	FreakOut(err)

	fmt.Printf("Route successfully deleted.")
}
func ListContextRoutes(cliConnection plugin.CliConnection, args []string) {
	mySpace, _ := cliConnection.GetCurrentSpace()

	output, err := cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("v2/spaces/%s/routes", mySpace.Guid))
	FreakOut(err)
	routes := RoutesModel{}
	err = json.Unmarshal([]byte(output[0]), &routes)
	FreakOut(err)

	table := NewTable([]string{"space", "host", "domain", "path", "apps"})
	for _, route := range routes.Resources {
		output, err := cliConnection.CliCommandWithoutTerminalOutput("curl", route.Entity.DomainUrl)
		FreakOut(err)
		domain := DomainModel{}
		err = json.Unmarshal([]byte(output[0]), &domain)
		FreakOut(err)

		output, err = cliConnection.CliCommandWithoutTerminalOutput("curl", route.Entity.AppsUrl)
		FreakOut(err)
		apps := AppsModel{}
		err = json.Unmarshal([]byte(output[0]), &apps)
		FreakOut(err)

		appNames := []string{}
		for _, app := range apps.Resources {
			appNames = append(appNames, app.Entity.Name)
		}

		table.Add(mySpace.Name, route.Entity.Host, domain.Entity.Name, route.Entity.Path, strings.Join(appNames, ","))
	}
	table.Print()
}