Skip to content

Commit

Permalink
Merge pull request #23 from ibuildthecloud/updates
Browse files Browse the repository at this point in the history
Updates
  • Loading branch information
ibuildthecloud authored Oct 11, 2016
2 parents f614ad6 + e6625e7 commit fade001
Show file tree
Hide file tree
Showing 33 changed files with 340 additions and 162 deletions.
135 changes: 105 additions & 30 deletions cmd/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,85 +2,160 @@ package cmd

import (
"archive/tar"
"fmt"
"bytes"
"io"
"io/ioutil"
"os"
"path/filepath"

"github.com/Sirupsen/logrus"
"github.com/rancher/go-rancher/v2"
"github.com/urfave/cli"
)

func ExportCommand() cli.Command {
return cli.Command{
Name: "export",
Usage: "Export configuration yml for a stack as a tar archive",
Description: "\nExports the docker-compose.yml and rancher-compose.yml for the specified stack as a tar archive.\n\nExample:\n\t$ rancher export mystack > files.tar\n\t$ rancher export -o files.tar mystack\n",
ArgsUsage: "[STACKNAME STACKID...]",
Action: exportService,
Name: "export",
Usage: "Export configuration yml for a stack as a tar archive or to local files",
Description: `
Exports the docker-compose.yml and rancher-compose.yml for the specified stack as a tar archive.
Example:
$ rancher export mystack
$ rancher export -f files.tar mystack
# Export the entire environment, including system stacks
$ rancher export --system mystack
`,
ArgsUsage: "[STACKNAME STACKID...]",
Action: exportService,
Flags: []cli.Flag{
cli.StringFlag{
Name: "output,o",
Usage: "Write to a file, instead of STDOUT",
Name: "file,f",
Usage: "Write to a file, instead of local files, use - to write to STDOUT",
},
cli.BoolFlag{
Name: "system",
Usage: "If exporting the entire environment, include system",
},
},
}
}

func getOutput(ctx *cli.Context) (io.WriteCloser, error) {
output := ctx.String("output")
output := ctx.String("file")
if output == "" {
return nil, nil
} else if output == "-" {
return os.Stdout, nil
}
return os.Create(output)
}

func exportService(ctx *cli.Context) error {
c, err := GetClient(ctx)
func getStackNames(ctx *cli.Context, c *client.RancherClient) ([]string, error) {
stacks, err := c.Stack.List(defaultListOpts(ctx))
if err != nil {
return err
return nil, err
}

if len(ctx.Args()) != 1 {
return fmt.Errorf("One stack name or ID is required as an argument")
result := []string{}
for _, stack := range stacks.Data {
result = append(result, stack.Name)
}

resource, err := Lookup(c, ctx.Args()[0], "environment")
if err != nil {
return err
}
return result, nil
}

env, err := c.Stack.ById(resource.Id)
func exportService(ctx *cli.Context) error {
var err error
c, err := GetClient(ctx)
if err != nil {
return err
}

config, err := c.Stack.ActionExportconfig(env, nil)
if err != nil {
return err
names := ctx.Args()
if len(names) == 0 {
names, err = getStackNames(ctx, c)
if err != nil {
return err
}
}

var archive *tar.Writer
output, err := getOutput(ctx)
if err != nil {
return err
}
defer output.Close()
if output != nil {
defer output.Close()
archive = tar.NewWriter(output)
defer archive.Close()
}

archive := tar.NewWriter(output)
defer archive.Close()
for _, name := range names {
resource, err := Lookup(c, name, "stack")
if err != nil {
return err
}

if err := addToTar(archive, "docker-compose.yml", config.DockerComposeConfig); err != nil {
return err
stack, err := c.Stack.ById(resource.Id)
if err != nil {
return err
}

if _, ok := stack.Actions["exportconfig"]; !ok {
continue
}

config, err := c.Stack.ActionExportconfig(stack, nil)
if err != nil {
return err
}

if err := addToTar(archive, stack.Name, "docker-compose.yml", config.DockerComposeConfig); err != nil {
return err
}
if err := addToTar(archive, stack.Name, "rancher-compose.yml", config.RancherComposeConfig); err != nil {
return err
}
if len(config.Actions) > 0 {
if err := addToTar(archive, stack.Name, "answers", marshalAnswers(config.Actions)); err != nil {
return err
}
}
}
return addToTar(archive, "rancher-compose.yml", config.RancherComposeConfig)

return nil
}

func marshalAnswers(answers map[string]string) string {
buf := &bytes.Buffer{}
for k, v := range answers {
buf.WriteString(k)
buf.WriteString("=")
buf.WriteString(v)
buf.WriteString("\n")
}
return buf.String()
}

func addToTar(archive *tar.Writer, name string, stringContent string) error {
func addToTar(archive *tar.Writer, stackName, name string, stringContent string) error {
if len(stringContent) == 0 {
return nil
}

f := filepath.Join(stackName, name)
if archive == nil {
err := os.MkdirAll(stackName, 0755)
if err != nil {
return err
}
logrus.Infof("Creating %s", f)
return ioutil.WriteFile(f, []byte(stringContent), 0600)
}

content := []byte(stringContent)
err := archive.WriteHeader(&tar.Header{
Name: name,
Name: f,
Size: int64(len(content)),
Mode: 0644,
Uname: "root",
Expand Down
6 changes: 3 additions & 3 deletions cmd/host_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func buildFlag(name string, field client.Field) cli.Flag {
func buildFlags(prefix string, schema client.Schema, schemas *client.Schemas) []cli.Flag {
flags := []cli.Flag{}
for name, field := range schema.ResourceFields {
if !field.Create || name == "name" {
if !field.Create || name == "hostname" {
continue
}

Expand Down Expand Up @@ -280,9 +280,9 @@ func hostCreateRun(ctx *cli.Context, c *client.RancherClient, machineSchema clie

var lastErr error
for _, name := range names {
args["name"] = name
args["hostname"] = name
var machine client.Machine
if err := c.Create("machine", args, &machine); err != nil {
if err := c.Create("host", args, &machine); err != nil {
lastErr = err
logrus.Error(err)
} else {
Expand Down
21 changes: 7 additions & 14 deletions cmd/ps.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"strings"

"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/rancher/go-rancher/v2"
"github.com/urfave/cli"
Expand All @@ -19,6 +18,7 @@ func PsCommand() cli.Command {
Action: servicePs,
Flags: []cli.Flag{
listAllFlag(),
listSystemFlag(),
cli.BoolFlag{
Name: "containers,c",
Usage: "Display containers",
Expand All @@ -37,7 +37,7 @@ func PsCommand() cli.Command {

func GetStackMap(c *client.RancherClient) map[string]client.Stack {
result := map[string]client.Stack{}
stacks, err := c.Stack.List(defaultListOpts(nil))
stacks, err := c.Stack.List(baseListOpts())
if err != nil {
return result
}
Expand All @@ -52,7 +52,7 @@ func GetStackMap(c *client.RancherClient) map[string]client.Stack {
type PsData struct {
Service client.Service
Name string
LaunchConfig client.LaunchConfig
LaunchConfig interface{}
Stack client.Stack
CombinedState string
ID string
Expand Down Expand Up @@ -93,6 +93,7 @@ func servicePs(ctx *cli.Context) error {
{"IMAGE", "LaunchConfig.ImageUuid"},
{"STATE", "CombinedState"},
{"SCALE", "{{len .Service.InstanceIds}}/{{.Service.Scale}}"},
{"SYSTEM", "Service.System"},
{"ENDPOINTS", "{{endpoint .Service.PublicEndpoints}}"},
{"DETAIL", "Service.TransitioningMessage"},
}, ctx)
Expand Down Expand Up @@ -120,22 +121,14 @@ func servicePs(ctx *cli.Context) error {
CombinedState: combined,
})
for _, sidekick := range item.SecondaryLaunchConfigs {
var sidekickLaunchConfig client.LaunchConfig
var sidekickSecondaryLaunchConfig client.SecondaryLaunchConfig
if err := mapstructure.Decode(sidekick, &sidekickLaunchConfig); err != nil {
return err
}
if err := mapstructure.Decode(sidekick, &sidekickSecondaryLaunchConfig); err != nil {
return err
}
sidekickLaunchConfig.ImageUuid = strings.TrimPrefix(sidekickLaunchConfig.ImageUuid, "docker:")
sidekick.ImageUuid = strings.TrimPrefix(sidekick.ImageUuid, "docker:")
item.Type = "sidekick"
writer.Write(PsData{
ID: item.Id,
Service: item,
Name: fmt.Sprintf("%s/%s/%s", stackMap[item.StackId].Name, item.Name,
sidekickSecondaryLaunchConfig.Name),
LaunchConfig: sidekickLaunchConfig,
sidekick.Name),
LaunchConfig: sidekick,
Stack: stackMap[item.StackId],
CombinedState: combined,
})
Expand Down
32 changes: 30 additions & 2 deletions cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,18 @@ func RunCommand() cli.Command {
Usage: "Number of containers to run",
Value: 1,
},
cli.BoolFlag{
Name: "schedule-global",
Usage: "Run 1 container per host",
},
cli.StringSliceFlag{
Name: "label,l",
Usage: "Add label in the form of key=value",
},
cli.BoolFlag{
Name: "pull",
Usage: "Always pull image on container start",
},
},
}
}
Expand Down Expand Up @@ -225,9 +237,8 @@ func serviceRun(ctx *cli.Context) error {
Expose: ctx.StringSlice("expose"),
Hostname: ctx.String("hostname"),
ImageUuid: "docker:" + ctx.Args()[0],
//Labels:
Labels: map[string]interface{}{},
//LogConfig:
//Lxc:
Memory: ctx.Int64("memory"),
MemorySwap: ctx.Int64("memory-swap"),
//NetworkIds: ctx.StringSlice("networkids"),
Expand Down Expand Up @@ -260,6 +271,23 @@ func serviceRun(ctx *cli.Context) error {
}
}

for _, label := range ctx.StringSlice("label") {
parts := strings.SplitN(label, "=", 1)
value := ""
if len(parts) > 1 {
value = parts[1]
}
launchConfig.Labels[parts[0]] = value
}

if ctx.Bool("schedule-global") {
launchConfig.Labels["io.rancher.scheduler.global"] = "true"
}

if ctx.Bool("pull") {
launchConfig.Labels["io.rancher.container.pull_image"] = "always"
}

args := ctx.Args()[1:]

if len(args) > 0 {
Expand Down
Loading

0 comments on commit fade001

Please sign in to comment.