Skip to content

Commit

Permalink
Merge pull request #31 from ibuildthecloud/fixes3
Browse files Browse the repository at this point in the history
Fixes
  • Loading branch information
ibuildthecloud authored Nov 30, 2016
2 parents c309e08 + ec76de3 commit 6e6ebec
Show file tree
Hide file tree
Showing 11 changed files with 224 additions and 48 deletions.
8 changes: 5 additions & 3 deletions cmd/catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,13 +382,15 @@ func GetCatalogClient(ctx *cli.Context) (*catalog.RancherClient, error) {
return nil, err
}

idx := strings.LastIndex(config.URL, "/v1")
idx := strings.LastIndex(config.URL, "/v2-beta")
if idx == -1 {
return nil, fmt.Errorf("Invalid URL %s, must contain /v1", config.URL)
return nil, fmt.Errorf("Invalid URL %s, must contain /v2-beta", config.URL)
}

url := config.URL[:idx] + "/v1-catalog/schemas"
return catalog.NewRancherClient(&catalog.ClientOpts{
Url: url,
AccessKey: config.AccessKey,
SecretKey: config.SecretKey,
Url: url,
})
}
2 changes: 1 addition & 1 deletion cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func ConfigCommand() cli.Command {
ArgsUsage: "None",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "print",
Name: "print,p",
Usage: "Print the current configuration",
},
},
Expand Down
192 changes: 172 additions & 20 deletions cmd/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package cmd

import (
"fmt"
"strings"
"io/ioutil"
"os"

"github.com/rancher/go-rancher/v2"
"github.com/urfave/cli"
"gopkg.in/yaml.v2"
)

func EnvCommand() cli.Command {
Expand Down Expand Up @@ -40,19 +42,54 @@ func EnvCommand() cli.Command {
Name: "create",
Usage: "Create an environment",
Description: `
By default, an environment with cattle orchestration framework will be created. This command only works for Account API keys.
By default, an environment with cattle orchestration framework will be created. This command only works with Account API keys.
Example:
$ rancher env create newEnv
To add an orchestration framework do TODO
$ rancher env create -o kubernetes newK8sEnv
$ rancher env create -o mesos newMesosEnv
$ rancher env create -o swarm newSwarmEnv
$ rancher env create -t kubernetes newK8sEnv
$ rancher env create -t mesos newMesosEnv
$ rancher env create -t swarm newSwarmEnv
`,
ArgsUsage: "[NEWENVNAME...]",
Action: envCreate,
Flags: []cli.Flag{
cli.StringFlag{
Name: "template,t",
Usage: "Environment template to create from",
Value: "Cattle",
},
},
},
cli.Command{
Name: "templates",
ShortName: "template",
Usage: "Interact with environment templates",
Action: defaultAction(envTemplateLs),
Flags: envLsFlags,
Subcommands: []cli.Command{
cli.Command{
Name: "export",
Usage: "Export an environment template to STDOUT",
ArgsUsage: "[TEMPLATEID TEMPLATENAME...]",
Action: envTemplateExport,
Flags: []cli.Flag{},
},
cli.Command{
Name: "import",
Usage: "Import an environment template to from file",
ArgsUsage: "[FILE FILE...]",
Action: envTemplateImport,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "public",
Usage: "Make template public",
},
},
},
},
},
cli.Command{
Name: "rm",
Expand Down Expand Up @@ -99,6 +136,11 @@ type EnvData struct {
Environment *client.Project
}

type TemplateData struct {
ID string
ProjectTemplate *client.ProjectTemplate
}

func NewEnvData(project client.Project) *EnvData {
return &EnvData{
ID: project.Id,
Expand Down Expand Up @@ -132,7 +174,14 @@ func envCreate(ctx *cli.Context) error {
"name": name,
}

setFields(ctx, data)
template := ctx.String("template")
if template != "" {
template, err := Lookup(c, template, "projectTemplate")
if err != nil {
return err
}
data["projectTemplateId"] = template.Id
}

var newEnv client.Project
if err := c.Create("project", data, &newEnv); err != nil {
Expand All @@ -143,20 +192,6 @@ func envCreate(ctx *cli.Context) error {
return nil
}

func setFields(ctx *cli.Context, data map[string]interface{}) {
orch := strings.ToLower(ctx.String("orchestration"))

data["swarm"] = false
data["kubernetes"] = false
data["mesos"] = false

if orch == "k8s" {
orch = "kubernetes"
}

data[orch] = true
}

func envLs(ctx *cli.Context) error {
c, err := GetRawClient(ctx)
if err != nil {
Expand Down Expand Up @@ -213,3 +248,120 @@ func envActivate(ctx *cli.Context) error {
return resource.Id, c.Action(resource.Type, action, resource, nil, resource)
})
}

func envTemplateLs(ctx *cli.Context) error {
c, err := GetRawClient(ctx)
if err != nil {
return err
}

writer := NewTableWriter([][]string{
{"ID", "ID"},
{"NAME", "ProjectTemplate.Name"},
{"DESC", "ProjectTemplate.Description"},
}, ctx)
defer writer.Close()

collection, err := c.ProjectTemplate.List(defaultListOpts(ctx))
if err != nil {
return err
}

for _, item := range collection.Data {
writer.Write(TemplateData{
ID: item.Id,
ProjectTemplate: &item,
})
}

return writer.Err()
}

func envTemplateImport(ctx *cli.Context) error {
c, err := GetRawClient(ctx)
if err != nil {
return err
}

w, err := NewWaiter(ctx)
if err != nil {
return err
}

for _, file := range ctx.Args() {
template := client.ProjectTemplate{
IsPublic: ctx.Bool("public"),
}
content, err := ioutil.ReadFile(file)
if err != nil {
return err
}

if err := yaml.Unmarshal(content, &template); err != nil {
return err
}

created, err := c.ProjectTemplate.Create(&template)
if err != nil {
return err
}

w.Add(created.Id)
}

return w.Wait()
}

func envTemplateExport(ctx *cli.Context) error {
c, err := GetRawClient(ctx)
if err != nil {
return err
}

for _, name := range ctx.Args() {
r, err := Lookup(c, name, "projectTemplate")
if err != nil {
return err
}

template, err := c.ProjectTemplate.ById(r.Id)
if err != nil {
return err
}

stacks := []map[string]interface{}{}
for _, s := range template.Stacks {
data := map[string]interface{}{
"name": s.Name,
}
if s.TemplateId != "" {
data["template_id"] = s.TemplateId
}
if s.TemplateVersionId != "" {
data["template_version_id"] = s.TemplateVersionId
}
if len(s.Answers) > 0 {
data["answers"] = s.Answers
}
stacks = append(stacks, data)
}

data := map[string]interface{}{
"name": template.Name,
"description": template.Description,
"stacks": stacks,
}

content, err := yaml.Marshal(&data)
if err != nil {
return err
}

_, err = os.Stdout.Write(content)
if err != nil {
return err
}
}

return nil
}
1 change: 1 addition & 0 deletions cmd/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
func EventsCommand() cli.Command {
return cli.Command{
Name: "events",
ShortName: "event",
Usage: "Displays resource change events",
Description: "\nOnly events that are actively occuring in Rancher are listed.\n",
ArgsUsage: "None",
Expand Down
2 changes: 1 addition & 1 deletion cmd/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Example:
Usage: "Write to a file, instead of local files, use - to write to STDOUT",
},
cli.BoolFlag{
Name: "system",
Name: "system,s",
Usage: "If exporting the entire environment, include system",
},
},
Expand Down
3 changes: 2 additions & 1 deletion cmd/host_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,9 @@ func hostCreateRun(ctx *cli.Context, c *client.RancherClient, machineSchema clie
continue
}

key = toAPI(strings.TrimPrefix(name, driver+"-"))

if strings.HasPrefix(name, driver+"-") {
key = toAPI(strings.TrimPrefix(name, driver+"-"))
schema = driverSchema
destArgs = driverArgs
}
Expand Down
10 changes: 9 additions & 1 deletion cmd/rm.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"fmt"
"strings"

"github.com/rancher/go-rancher/v2"
Expand Down Expand Up @@ -49,6 +50,13 @@ func deleteResources(ctx *cli.Context) error {
}
}
}
return resource.Id, c.Delete(resource)
err := c.Delete(resource)
if v, ok := err.(*client.ApiError); ok && v.StatusCode == 405 {
action, err := pickAction(resource, "stop", "deactivate")
if err == nil {
fmt.Printf("error: Must call %s on %s %s before removing\n", action, resource.Type, resource.Id)
}
}
return resource.Id, err
})
}
37 changes: 19 additions & 18 deletions cmd/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ func hostSSH(ctx *cli.Context) error {
return err
}

config, err := lookupConfig(ctx)
if err != nil {
return err
}

hostname := ""
args := ctx.Args()

Expand All @@ -53,36 +58,26 @@ func hostSSH(ctx *cli.Context) error {
return fmt.Errorf("Failed to find hostname in %v", args)
}

host, err := Lookup(c, hostname, "host")
hostResource, err := Lookup(c, hostname, "host")
if err != nil {
return err
}

var physicalHost client.PhysicalHost
err = c.GetLink(*host, "physicalHost", &physicalHost)
host, err := c.Host.ById(hostResource.Id)
if err != nil {
return err
}

if physicalHost.Type != "machine" {
return fmt.Errorf("Can only SSH to docker-machine created hosts. No custom hosts")
}

key, err := getSSHKey(hostname, physicalHost)
key, err := getSSHKey(hostname, *host, config.AccessKey, config.SecretKey)
if err != nil {
return err
}

ips := client.IpAddressCollection{}
if err := c.GetLink(*host, "ipAddresses", &ips); err != nil {
return err
}

if len(ips.Data) == 0 {
if host.AgentIpAddress == "" {
return fmt.Errorf("Failed to find IP for %s", hostname)
}

return processExitCode(callSSH(key, ips.Data[0].Address, ctx.Args()))
return processExitCode(callSSH(key, host.AgentIpAddress, ctx.Args()))
}

func callSSH(content []byte, ip string, args []string) error {
Expand Down Expand Up @@ -121,13 +116,19 @@ func callSSH(content []byte, ip string, args []string) error {
return cmd.Run()
}

func getSSHKey(hostname string, physicalHost client.PhysicalHost) ([]byte, error) {
link, ok := physicalHost.Links["config"]
func getSSHKey(hostname string, host client.Host, accessKey, secretKey string) ([]byte, error) {
link, ok := host.Links["config"]
if !ok {
return nil, fmt.Errorf("Failed to find SSH key for %s", hostname)
}

resp, err := http.Get(link)
req, err := http.NewRequest("GET", link, nil)
if err != nil {
return nil, err
}
req.SetBasicAuth(accessKey, secretKey)

resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
Expand Down
Loading

0 comments on commit 6e6ebec

Please sign in to comment.