Skip to content

Commit

Permalink
Merge pull request #14 from ibuildthecloud/refactor
Browse files Browse the repository at this point in the history
Refactor
  • Loading branch information
ibuildthecloud authored Aug 18, 2016
2 parents 977b7c2 + 1eaf0f3 commit 875664a
Show file tree
Hide file tree
Showing 26 changed files with 514 additions and 365 deletions.
57 changes: 35 additions & 22 deletions cmd/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"syscall"
"text/template"

"github.com/Sirupsen/logrus"
"github.com/docker/docker/pkg/namesgenerator"
"github.com/rancher/go-rancher/client"
"github.com/urfave/cli"
Expand All @@ -27,13 +26,12 @@ func GetRawClient(ctx *cli.Context) (*client.RancherClient, error) {
if err != nil {
return nil, err
}
idx := strings.LastIndex(config.URL, "/v1")
if idx == -1 {
return nil, fmt.Errorf("Invalid URL %s, must contain /v1", config.URL)
url, err := baseURL(config.URL)
if err != nil {
return nil, err
}

return client.NewRancherClient(&client.ClientOpts{
Url: config.URL[:idx] + "/v1",
Url: url + "/v1",
AccessKey: config.AccessKey,
SecretKey: config.SecretKey,
})
Expand Down Expand Up @@ -155,6 +153,25 @@ func GetOrCreateDefaultStack(c *client.RancherClient, name string) (*client.Envi
})
}

func getProjectByName(c *client.RancherClient, name string) (client.ResourceCollection, error) {
var result client.ResourceCollection
err := c.List("account", &client.ListOpts{
Filters: map[string]interface{}{
"kind": "project",
"limit": "-2",
"name": name,
},
}, &result)
for i, resource := range result.Data {
err := c.ById("project", resource.Id, &resource)
if err != nil {
return result, err
}
result.Data[i] = resource
}
return result, err
}

func getHostByHostname(c *client.RancherClient, name string) (client.ResourceCollection, error) {
var result client.ResourceCollection
allHosts, err := c.Host.List(nil)
Expand Down Expand Up @@ -208,13 +225,16 @@ func Lookup(c *client.RancherClient, name string, types ...string) (*client.Reso
}

var collection client.ResourceCollection
if err := c.List(schemaType, &client.ListOpts{
Filters: map[string]interface{}{
"name": name,
"removed_null": 1,
},
}, &collection); err != nil {
return nil, err
// search by name for project doesn't work
if schemaType != "project" {
if err := c.List(schemaType, &client.ListOpts{
Filters: map[string]interface{}{
"name": name,
"removed_null": 1,
},
}, &collection); err != nil {
return nil, err
}
}

if len(collection.Data) > 1 {
Expand All @@ -229,6 +249,8 @@ func Lookup(c *client.RancherClient, name string, types ...string) (*client.Reso
var err error
// Per type specific logic
switch schemaType {
case "project":
collection, err = getProjectByName(c, name)
case "host":
collection, err = getHostByHostname(c, name)
case "service":
Expand Down Expand Up @@ -285,15 +307,6 @@ func SimpleFormat(values [][]string) (string, string) {
return headerBuffer.String(), valueBuffer.String()
}

func errorWrapper(f func(*cli.Context) error) func(*cli.Context) error {
return func(ctx *cli.Context) error {
if err := f(ctx); err != nil {
logrus.Fatal(err)
}
return nil
}
}

func defaultAction(fn func(ctx *cli.Context) error) func(ctx *cli.Context) error {
return func(ctx *cli.Context) error {
if ctx.Bool("help") {
Expand Down
28 changes: 22 additions & 6 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"os"
"path"
"strings"
Expand All @@ -22,6 +23,22 @@ type Config struct {
Path string `json:"path,omitempty"`
}

func baseURL(fullURL string) (string, error) {
idx := strings.LastIndex(fullURL, "/v1")
if idx == -1 {
u, err := url.Parse(fullURL)
if err != nil {
return "", err
}
newURL := url.URL{
Scheme: u.Scheme,
Host: u.Host,
}
return newURL.String(), nil
}
return fullURL[:idx], nil
}

func (c Config) EnvironmentURL() (string, error) {
projectID := c.Environment
if projectID == "" || !strings.HasPrefix(projectID, "1a") {
Expand All @@ -40,12 +57,11 @@ func (c Config) EnvironmentURL() (string, error) {
projectID = project.Id
}

idx := strings.LastIndex(c.URL, "/v1")
if idx == -1 {
return "", fmt.Errorf("Invalid URL %s, must contain /v1", c.URL)
url, err := baseURL(c.URL)
if err != nil {
return "", err
}

url := c.URL[:idx] + "/v1/projects/" + projectID + "/schemas"
url = url + "/v1/projects/" + projectID + "/schemas"
return url, nil
}

Expand Down Expand Up @@ -89,7 +105,7 @@ func ConfigCommand() cli.Command {
return cli.Command{
Name: "config",
Usage: "Setup client configuration",
Action: errorWrapper(configSetup),
Action: configSetup,
ArgsUsage: "None",
Flags: []cli.Flag{
cli.BoolFlag{
Expand Down
52 changes: 0 additions & 52 deletions cmd/container.go

This file was deleted.

101 changes: 71 additions & 30 deletions cmd/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"strings"

"github.com/Sirupsen/logrus"
"github.com/rancher/go-rancher/client"
"github.com/urfave/cli"
)
Expand All @@ -21,8 +20,9 @@ func EnvCommand() cli.Command {
Usage: "List environments",
Description: "\nWith an account API key, all environments in Rancher will be listed. If you are using an environment API key, it will only list the environment of the API key. \n\nExample:\n\t$ rancher env ls\n",
ArgsUsage: "None",
Action: errorWrapper(envLs),
Action: envLs,
Flags: []cli.Flag{
listAllFlag(),
cli.BoolFlag{
Name: "quiet,q",
Usage: "Only display IDs",
Expand All @@ -38,7 +38,7 @@ func EnvCommand() cli.Command {
Usage: "Create an environment",
Description: "\nBy default, an environment with cattle orchestration framework will be created. This command only works for Account API keys.\n\nExample:\n\t$ rancher env create newEnv\n\t$ rancher env create -o kubernetes newK8sEnv\n\t$ rancher env create -o mesos newMesosEnv\n\t$ rancher env create -o swarm newSwarmEnv\n",
ArgsUsage: "[NEWENVNAME...]",
Action: errorWrapper(envCreate),
Action: envCreate,
Flags: []cli.Flag{
cli.StringFlag{
Name: "orchestration,o",
Expand All @@ -51,22 +51,50 @@ func EnvCommand() cli.Command {
Usage: "Remove environment(s)",
Description: "\nExample:\n\t$ rancher env rm 1a5\n\t$ rancher env rm newEnv\n",
ArgsUsage: "[ENVID ENVNAME...]",
Action: errorWrapper(envRm),
Action: envRm,
Flags: []cli.Flag{},
},
cli.Command{
Name: "update",
Usage: "Update environment",
Description: "\nChange the orchestration framework of the environment. This command only works for Account API keys.\n\nExample:\n\t$ rancher env update -o kubernetes 1a5\n\t$ rancher env update -o cattle Default\n\t$ rancher env update -o swarm 1a5\n\t$ rancher env update -o mesos 1a5\n",
ArgsUsage: "[ENVID ENVNAME...]",
Action: errorWrapper(envUpdate),
Action: envUpdate,
Flags: []cli.Flag{
cli.StringFlag{
Name: "orchestration,o",
Usage: "Orchestration framework",
},
},
},
cli.Command{
Name: "deactivate",
Usage: "Deactivate environment(s)",
Description: `
Deactivate an environment by ID or name
Example:
$ rancher env deactivate 1a5
$ rancher env deactivate Default
`,
ArgsUsage: "[ID NAME...]",
Action: envDeactivate,
Flags: []cli.Flag{},
},
cli.Command{
Name: "activate",
Usage: "Activate environment(s)",
Description: `
Activate an environment by ID or name
Example:
$ rancher env activate 1a5
$ rancher env activate Default
`,
ArgsUsage: "[ID NAME...]",
Action: envActivate,
Flags: []cli.Flag{},
},
},
}
}
Expand Down Expand Up @@ -102,23 +130,9 @@ func envRm(ctx *cli.Context) error {
return err
}

var lastErr error
for _, id := range ctx.Args() {
env, err := Lookup(c, id, "account")
if err != nil {
logrus.Errorf("Failed to delete %s: %v", id, err)
lastErr = err
continue
}
if err := c.Delete(env); err != nil {
logrus.Errorf("Failed to delete %s: %v", id, err)
lastErr = err
continue
}
fmt.Println(env.Id)
}

return lastErr
return forEachResourceWithClient(c, ctx, []string{"project"}, func(c *client.RancherClient, resource *client.Resource) (string, error) {
return resource.Id, c.Delete(resource)
})
}

func envUpdate(ctx *cli.Context) error {
Expand Down Expand Up @@ -151,7 +165,7 @@ func envUpdate(ctx *cli.Context) error {
return err
}

fmt.Println(env.Name + " (" + env.Id + ")")
fmt.Println(env.Id)
return nil
}

Expand All @@ -177,7 +191,7 @@ func envCreate(ctx *cli.Context) error {
return err
}

fmt.Println(newEnv.Name + " (" + newEnv.Id + ")")
fmt.Println(newEnv.Id)
return nil
}

Expand Down Expand Up @@ -211,12 +225,9 @@ func envLs(ctx *cli.Context) error {
defer writer.Close()

collection := client.ProjectCollection{}
err = c.List("account", &client.ListOpts{
Filters: map[string]interface{}{
"kind": "project",
},
}, &collection)
if err != nil {
listOpts := defaultListOpts(ctx)
listOpts.Filters["kind"] = "project"
if err = c.List("account", listOpts, &collection); err != nil {
return err
}

Expand All @@ -226,3 +237,33 @@ func envLs(ctx *cli.Context) error {

return writer.Err()
}

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

return forEachResourceWithClient(c, ctx, []string{"project"}, func(c *client.RancherClient, resource *client.Resource) (string, error) {
action, err := pickAction(resource, "deactivate")
if err != nil {
return "", err
}
return resource.Id, c.Action(resource.Type, action, resource, nil, resource)
})
}

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

return forEachResourceWithClient(c, ctx, []string{"project"}, func(c *client.RancherClient, resource *client.Resource) (string, error) {
action, err := pickAction(resource, "activate")
if err != nil {
return "", err
}
return resource.Id, c.Action(resource.Type, action, resource, nil, resource)
})
}
Loading

0 comments on commit 875664a

Please sign in to comment.