<commit_before>package main

import (
	"fmt"
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/codegangsta/cli"
	"github.com/ingrammicro/concerto/audit"
	"github.com/ingrammicro/concerto/blueprint/scripts"
	"github.com/ingrammicro/concerto/blueprint/services"
	"github.com/ingrammicro/concerto/blueprint/templates"
	"github.com/ingrammicro/concerto/brownfield"
	cl_prov "github.com/ingrammicro/concerto/cloud/cloud_providers"
	"github.com/ingrammicro/concerto/cloud/generic_images"
	"github.com/ingrammicro/concerto/cloud/saas_providers"
	"github.com/ingrammicro/concerto/cloud/server_plan"
	"github.com/ingrammicro/concerto/cloud/servers"
	"github.com/ingrammicro/concerto/cloud/ssh_profiles"
	"github.com/ingrammicro/concerto/cloud/workspaces"
	"github.com/ingrammicro/concerto/cluster"
	"github.com/ingrammicro/concerto/cmdpolling"
	"github.com/ingrammicro/concerto/converge"
	"github.com/ingrammicro/concerto/dispatcher"
	"github.com/ingrammicro/concerto/firewall"
	"github.com/ingrammicro/concerto/network/firewall_profiles"
	"github.com/ingrammicro/concerto/node"
	"github.com/ingrammicro/concerto/settings/cloud_accounts"
	"github.com/ingrammicro/concerto/setup"
	"github.com/ingrammicro/concerto/utils"
	"github.com/ingrammicro/concerto/utils/format"
	"github.com/ingrammicro/concerto/wizard/apps"
	"github.com/ingrammicro/concerto/wizard/cloud_providers"
	"github.com/ingrammicro/concerto/wizard/locations"
	"github.com/ingrammicro/concerto/wizard/server_plans"
)

var ServerCommands = []cli.Command{
	{
		Name:  "firewall",
		Usage: "Manages Firewall Policies within a Host",
		Subcommands: append(
			firewall.SubCommands(),
		),
	},
	{
		Name:  "scripts",
		Usage: "Manages Execution Scripts within a Host",
		Subcommands: append(
			dispatcher.SubCommands(),
		),
	},
	{
		Name:   "converge",
		Usage:  "Converges Host to original Blueprint",
		Action: converge.CmbConverge,
	},
	{
		Name:  "brownfield",
		Usage: "Manages registration and configuration within an imported brownfield Host",
		Subcommands: append(
			brownfield.SubCommands(),
		),
	},
	{
		Name:  "polling",
		Usage: "Manages polling commands",
		Subcommands: append(
			cmdpolling.SubCommands(),
		),
	},
}

var BlueprintCommands = []cli.Command{
	{
		Name:  "scripts",
		Usage: "Allow the user to manage the scripts they want to run on the servers",
		Subcommands: append(
			scripts.SubCommands(),
		),
	},
	{
		Name:  "services",
		Usage: "Provides information on services",
		Subcommands: append(
			services.SubCommands(),
		),
	},
	{
		Name:  "templates",
		Usage: "Provides information on templates",
		Subcommands: append(
			templates.SubCommands(),
		),
	},
}

var CloudCommands = []cli.Command{
	{
		Name:  "workspaces",
		Usage: "Provides information on workspaces",
		Subcommands: append(
			workspaces.SubCommands(),
		),
	},
	{
		Name:  "servers",
		Usage: "Provides information on servers",
		Subcommands: append(
			servers.SubCommands(),
		),
	},
	{
		Name:  "generic_images",
		Usage: "Provides information on generic images",
		Subcommands: append(
			generic_images.SubCommands(),
		),
	},
	{
		Name:  "ssh_profiles",
		Usage: "Provides information on SSH profiles",
		Subcommands: append(
			ssh_profiles.SubCommands(),
		),
	},
	{
		Name:  "cloud_providers",
		Usage: "Provides information on cloud providers",
		Subcommands: append(
			cl_prov.SubCommands(),
		),
	},
	{
		Name:  "server_plans",
		Usage: "Provides information on server plans",
		Subcommands: append(
			server_plan.SubCommands(),
		),
	},
	{
		Name:  "saas_providers",
		Usage: "Provides information about SAAS providers",
		Subcommands: append(
			saas_providers.SubCommands(),
		),
	},
}

var NetCommands = []cli.Command{
	{
		Name:  "firewall_profiles",
		Usage: "Provides information about firewall profiles",
		Subcommands: append(
			firewall_profiles.SubCommands(),
		),
	},
}

var SettingsCommands = []cli.Command{
	{
		Name:  "cloud_accounts",
		Usage: "Provides information about cloud accounts",
		Subcommands: append(
			cloud_accounts.SubCommands(),
		),
	},
}

var WizardCommands = []cli.Command{
	{
		Name:  "apps",
		Usage: "Provides information about apps",
		Subcommands: append(
			apps.SubCommands(),
		),
	},
	{
		Name:  "cloud_providers",
		Usage: "Provides information about cloud providers",
		Subcommands: append(
			cloud_providers.SubCommands(),
		),
	},
	{
		Name:  "locations",
		Usage: "Provides information about locations",
		Subcommands: append(
			locations.SubCommands(),
		),
	},
	{
		Name:  "server_plans",
		Usage: "Provides information about server plans",
		Subcommands: append(
			server_plans.SubCommands(),
		),
	},
}

var ClientCommands = []cli.Command{
	{
		Name:      "setup",
		ShortName: "se",
		Usage:     "Configures and setups concerto cli enviroment",
		Subcommands: append(
			setup.SubCommands(),
		),
	},
	{
		Name:      "nodes",
		ShortName: "no",
		Usage:     "Manages Docker Nodes",
		Subcommands: append(
			node.SubCommands(),
		),
	},
	{
		Name:      "cluster",
		ShortName: "clu",
		Usage:     "Manages a Kubernetes Cluster",
		Subcommands: append(
			cluster.SubCommands(),
		),
	},
	{
		Name:      "events",
		ShortName: "ev",
		Usage:     "Events allow the user to track their actions and the state of their servers",
		Subcommands: append(
			audit.SubCommands(),
		),
	},

	{
		Name:      "blueprint",
		ShortName: "bl",
		Usage:     "Manages blueprint commands for scripts, services and templates",
		Subcommands: append(
			BlueprintCommands,
		),
	},
	{
		Name:      "cloud",
		ShortName: "clo",
		Usage:     "Manages cloud related commands for workspaces, servers, generic images, ssh profiles, cloud providers, server plans and Saas providers",
		Subcommands: append(
			CloudCommands,
		),
	},
	{
		Name:      "network",
		ShortName: "net",
		Usage:     "Manages network related commands for firewall profiles",
		Subcommands: append(
			NetCommands,
		),
	},
	{
		Name:      "settings",
		ShortName: "set",
		Usage:     "Provides settings for cloud accounts",
		Subcommands: append(
			SettingsCommands,
		),
	},
	{
		Name:      "wizard",
		ShortName: "wiz",
		Usage:     "Manages wizard related commands for apps, locations, cloud providers, server plans",
		Subcommands: append(
			WizardCommands,
		),
	},
}

func cmdNotFound(c *cli.Context, command string) {
	log.Fatalf(
		"%s: '%s' is not a %s command. See '%s --help'.",
		c.App.Name,
		command,
		c.App.Name,
		c.App.Name,
	)
}

func prepareFlags(c *cli.Context) error {

	if c.Bool("debug") {
		os.Setenv("DEBUG", "1")
		log.SetOutput(os.Stderr)
		log.SetLevel(log.DebugLevel)
	}

	// try to read configuration
	config, err := utils.InitializeConcertoConfig(c)
	if err != nil {
		log.Errorf("Error reading Concerto configuration: %s", err)
		return err
	}

	// validate formatter
	if c.String("formatter") != "text" && c.String("formatter") != "json" {
		log.Errorf("Unrecognized formatter %s. Please, use one of [ text | json ]", c.String("formatter"))
		return fmt.Errorf("Unrecognized formatter %s. Please, use one of [ text | json ]", c.String("formatter"))
	}
	format.InitializeFormatter(c.String("formatter"), os.Stdout)

	if config.IsHost || config.BrownfieldToken != "" || config.CommandPollingToken != "" {
		log.Debug("Setting server commands to concerto")
		c.App.Commands = ServerCommands
	} else {
		log.Debug("Setting client commands to concerto")
		c.App.Commands = ClientCommands
	}

	// hack: substitute commands in category ... we should evaluate cobra/viper
	cat := c.App.Categories()

	for _, category := range cat {
		category.Commands = category.Commands[:0]
	}

	for _, command := range c.App.Commands {
		cat = cat.AddCommand(command.Category, command)
	}

	return nil
}

func main() {

	app := cli.NewApp()
	app.Name = "concerto"
	app.Author = "Concerto Contributors"
	app.Email = "https://github.com/ingrammicro/concerto"

	app.CommandNotFound = cmdNotFound
	app.Usage = "Manages communication between Host and Concerto Platform"
	app.Version = utils.VERSION

	app.Before = prepareFlags

	// set client commands by default to populate categories
	app.Commands = ClientCommands

	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "debug, D",
			Usage: "Enable debug mode",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_CA_CERT",
			Name:   "ca-cert",
			Usage:  "CA to verify remote connections",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_CLIENT_CERT",
			Name:   "client-cert",
			Usage:  "Client cert to use for Concerto",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_CLIENT_KEY",
			Name:   "client-key",
			Usage:  "Private key used in client Concerto auth",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_CONFIG",
			Name:   "concerto-config",
			Usage:  "Concerto Config File",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_ENDPOINT",
			Name:   "concerto-endpoint",
			Usage:  "Concerto Endpoint",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_URL",
			Name:   "concerto-url",
			Usage:  "Concerto Web URL",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_BROWNFIELD_TOKEN",
			Name:   "concerto-brownfield-token",
			Usage:  "Concerto Brownfield Token",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_COMMAND_POLLING_TOKEN",
			Name:   "concerto-command-polling-token",
			Usage:  "Concerto Command Polling Token",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_SERVER_ID",
			Name:   "concerto-server-id",
			Usage:  "Concerto Server ID",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_FORMATTER",
			Name:   "formatter",
			Usage:  "Output formatter [ text | json ] ",
			Value:  "text",
		},
	}

	app.Run(os.Args)

}
<commit_msg>Remove Kubernetes clusters and nodes commands (issue #52)<commit_after>package main

import (
	"fmt"
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/codegangsta/cli"
	"github.com/ingrammicro/concerto/audit"
	"github.com/ingrammicro/concerto/blueprint/scripts"
	"github.com/ingrammicro/concerto/blueprint/services"
	"github.com/ingrammicro/concerto/blueprint/templates"
	"github.com/ingrammicro/concerto/brownfield"
	cl_prov "github.com/ingrammicro/concerto/cloud/cloud_providers"
	"github.com/ingrammicro/concerto/cloud/generic_images"
	"github.com/ingrammicro/concerto/cloud/saas_providers"
	"github.com/ingrammicro/concerto/cloud/server_plan"
	"github.com/ingrammicro/concerto/cloud/servers"
	"github.com/ingrammicro/concerto/cloud/ssh_profiles"
	"github.com/ingrammicro/concerto/cloud/workspaces"
	"github.com/ingrammicro/concerto/cmdpolling"
	"github.com/ingrammicro/concerto/converge"
	"github.com/ingrammicro/concerto/dispatcher"
	"github.com/ingrammicro/concerto/firewall"
	"github.com/ingrammicro/concerto/network/firewall_profiles"
	"github.com/ingrammicro/concerto/settings/cloud_accounts"
	"github.com/ingrammicro/concerto/setup"
	"github.com/ingrammicro/concerto/utils"
	"github.com/ingrammicro/concerto/utils/format"
	"github.com/ingrammicro/concerto/wizard/apps"
	"github.com/ingrammicro/concerto/wizard/cloud_providers"
	"github.com/ingrammicro/concerto/wizard/locations"
	"github.com/ingrammicro/concerto/wizard/server_plans"
)

var ServerCommands = []cli.Command{
	{
		Name:  "firewall",
		Usage: "Manages Firewall Policies within a Host",
		Subcommands: append(
			firewall.SubCommands(),
		),
	},
	{
		Name:  "scripts",
		Usage: "Manages Execution Scripts within a Host",
		Subcommands: append(
			dispatcher.SubCommands(),
		),
	},
	{
		Name:   "converge",
		Usage:  "Converges Host to original Blueprint",
		Action: converge.CmbConverge,
	},
	{
		Name:  "brownfield",
		Usage: "Manages registration and configuration within an imported brownfield Host",
		Subcommands: append(
			brownfield.SubCommands(),
		),
	},
	{
		Name:  "polling",
		Usage: "Manages polling commands",
		Subcommands: append(
			cmdpolling.SubCommands(),
		),
	},
}

var BlueprintCommands = []cli.Command{
	{
		Name:  "scripts",
		Usage: "Allow the user to manage the scripts they want to run on the servers",
		Subcommands: append(
			scripts.SubCommands(),
		),
	},
	{
		Name:  "services",
		Usage: "Provides information on services",
		Subcommands: append(
			services.SubCommands(),
		),
	},
	{
		Name:  "templates",
		Usage: "Provides information on templates",
		Subcommands: append(
			templates.SubCommands(),
		),
	},
}

var CloudCommands = []cli.Command{
	{
		Name:  "workspaces",
		Usage: "Provides information on workspaces",
		Subcommands: append(
			workspaces.SubCommands(),
		),
	},
	{
		Name:  "servers",
		Usage: "Provides information on servers",
		Subcommands: append(
			servers.SubCommands(),
		),
	},
	{
		Name:  "generic_images",
		Usage: "Provides information on generic images",
		Subcommands: append(
			generic_images.SubCommands(),
		),
	},
	{
		Name:  "ssh_profiles",
		Usage: "Provides information on SSH profiles",
		Subcommands: append(
			ssh_profiles.SubCommands(),
		),
	},
	{
		Name:  "cloud_providers",
		Usage: "Provides information on cloud providers",
		Subcommands: append(
			cl_prov.SubCommands(),
		),
	},
	{
		Name:  "server_plans",
		Usage: "Provides information on server plans",
		Subcommands: append(
			server_plan.SubCommands(),
		),
	},
	{
		Name:  "saas_providers",
		Usage: "Provides information about SAAS providers",
		Subcommands: append(
			saas_providers.SubCommands(),
		),
	},
}

var NetCommands = []cli.Command{
	{
		Name:  "firewall_profiles",
		Usage: "Provides information about firewall profiles",
		Subcommands: append(
			firewall_profiles.SubCommands(),
		),
	},
}

var SettingsCommands = []cli.Command{
	{
		Name:  "cloud_accounts",
		Usage: "Provides information about cloud accounts",
		Subcommands: append(
			cloud_accounts.SubCommands(),
		),
	},
}

var WizardCommands = []cli.Command{
	{
		Name:  "apps",
		Usage: "Provides information about apps",
		Subcommands: append(
			apps.SubCommands(),
		),
	},
	{
		Name:  "cloud_providers",
		Usage: "Provides information about cloud providers",
		Subcommands: append(
			cloud_providers.SubCommands(),
		),
	},
	{
		Name:  "locations",
		Usage: "Provides information about locations",
		Subcommands: append(
			locations.SubCommands(),
		),
	},
	{
		Name:  "server_plans",
		Usage: "Provides information about server plans",
		Subcommands: append(
			server_plans.SubCommands(),
		),
	},
}

var ClientCommands = []cli.Command{
	{
		Name:      "setup",
		ShortName: "se",
		Usage:     "Configures and setups concerto cli enviroment",
		Subcommands: append(
			setup.SubCommands(),
		),
	},
	{
		Name:      "events",
		ShortName: "ev",
		Usage:     "Events allow the user to track their actions and the state of their servers",
		Subcommands: append(
			audit.SubCommands(),
		),
	},

	{
		Name:      "blueprint",
		ShortName: "bl",
		Usage:     "Manages blueprint commands for scripts, services and templates",
		Subcommands: append(
			BlueprintCommands,
		),
	},
	{
		Name:      "cloud",
		ShortName: "clo",
		Usage:     "Manages cloud related commands for workspaces, servers, generic images, ssh profiles, cloud providers, server plans and Saas providers",
		Subcommands: append(
			CloudCommands,
		),
	},
	{
		Name:      "network",
		ShortName: "net",
		Usage:     "Manages network related commands for firewall profiles",
		Subcommands: append(
			NetCommands,
		),
	},
	{
		Name:      "settings",
		ShortName: "set",
		Usage:     "Provides settings for cloud accounts",
		Subcommands: append(
			SettingsCommands,
		),
	},
	{
		Name:      "wizard",
		ShortName: "wiz",
		Usage:     "Manages wizard related commands for apps, locations, cloud providers, server plans",
		Subcommands: append(
			WizardCommands,
		),
	},
}

func cmdNotFound(c *cli.Context, command string) {
	log.Fatalf(
		"%s: '%s' is not a %s command. See '%s --help'.",
		c.App.Name,
		command,
		c.App.Name,
		c.App.Name,
	)
}

func prepareFlags(c *cli.Context) error {

	if c.Bool("debug") {
		os.Setenv("DEBUG", "1")
		log.SetOutput(os.Stderr)
		log.SetLevel(log.DebugLevel)
	}

	// try to read configuration
	config, err := utils.InitializeConcertoConfig(c)
	if err != nil {
		log.Errorf("Error reading Concerto configuration: %s", err)
		return err
	}

	// validate formatter
	if c.String("formatter") != "text" && c.String("formatter") != "json" {
		log.Errorf("Unrecognized formatter %s. Please, use one of [ text | json ]", c.String("formatter"))
		return fmt.Errorf("Unrecognized formatter %s. Please, use one of [ text | json ]", c.String("formatter"))
	}
	format.InitializeFormatter(c.String("formatter"), os.Stdout)

	if config.IsHost || config.BrownfieldToken != "" || config.CommandPollingToken != "" {
		log.Debug("Setting server commands to concerto")
		c.App.Commands = ServerCommands
	} else {
		log.Debug("Setting client commands to concerto")
		c.App.Commands = ClientCommands
	}

	// hack: substitute commands in category ... we should evaluate cobra/viper
	cat := c.App.Categories()

	for _, category := range cat {
		category.Commands = category.Commands[:0]
	}

	for _, command := range c.App.Commands {
		cat = cat.AddCommand(command.Category, command)
	}

	return nil
}

func main() {

	app := cli.NewApp()
	app.Name = "concerto"
	app.Author = "Concerto Contributors"
	app.Email = "https://github.com/ingrammicro/concerto"

	app.CommandNotFound = cmdNotFound
	app.Usage = "Manages communication between Host and Concerto Platform"
	app.Version = utils.VERSION

	app.Before = prepareFlags

	// set client commands by default to populate categories
	app.Commands = ClientCommands

	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "debug, D",
			Usage: "Enable debug mode",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_CA_CERT",
			Name:   "ca-cert",
			Usage:  "CA to verify remote connections",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_CLIENT_CERT",
			Name:   "client-cert",
			Usage:  "Client cert to use for Concerto",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_CLIENT_KEY",
			Name:   "client-key",
			Usage:  "Private key used in client Concerto auth",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_CONFIG",
			Name:   "concerto-config",
			Usage:  "Concerto Config File",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_ENDPOINT",
			Name:   "concerto-endpoint",
			Usage:  "Concerto Endpoint",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_URL",
			Name:   "concerto-url",
			Usage:  "Concerto Web URL",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_BROWNFIELD_TOKEN",
			Name:   "concerto-brownfield-token",
			Usage:  "Concerto Brownfield Token",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_COMMAND_POLLING_TOKEN",
			Name:   "concerto-command-polling-token",
			Usage:  "Concerto Command Polling Token",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_SERVER_ID",
			Name:   "concerto-server-id",
			Usage:  "Concerto Server ID",
		},
		cli.StringFlag{
			EnvVar: "CONCERTO_FORMATTER",
			Name:   "formatter",
			Usage:  "Output formatter [ text | json ] ",
			Value:  "text",
		},
	}

	app.Run(os.Args)

}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
)

func check(e error, s string) {
	if e != nil {
		fmt.Fprintf(os.Stderr, s, e)
		os.Exit(1)
	}
}

func main() {
	// size of image x and y
	nx := 400
	ny := 300

	const color = 255.99

	f, err := os.Create("out.ppm")

	defer f.Close()

	check(err, "Error opening file: %v\n")

	// http://netpbm.sourceforge.net/doc/ppm.html
	_, err = fmt.Fprintf(f, "P3\n%d %d\n255\n", nx, ny)

	check(err, "Error writting to file: %v\n")

	// writes each pixel with r/g/b values
	// from top left to bottom right
	for j := ny - 1; j >= 0; j-- {
		for i := 0; i < nx; i++ {
			// red and green values range from
			// 0.0 to 1.0
			v := Vector{X: float64(i) / float64(nx), Y: float64(j) / float64(ny), Z: 0.2}

			// get intensity of colors
			ir := int(color * v.X)
			ig := int(color * v.Y)
			ib := int(color * v.Z)

			_, err = fmt.Fprintf(f, "%d %d %d\n", ir, ig, ib)

			check(err, "Error writting to file: %v\n")
		}
	}
}
<commit_msg>Writing has 1 t<commit_after>package main

import (
	"fmt"
	"os"
)

func check(e error, s string) {
	if e != nil {
		fmt.Fprintf(os.Stderr, s, e)
		os.Exit(1)
	}
}

func main() {
	// size of image x and y
	nx := 400
	ny := 300

	const color = 255.99

	f, err := os.Create("out.ppm")

	defer f.Close()

	check(err, "Error opening file: %v\n")

	// http://netpbm.sourceforge.net/doc/ppm.html
	_, err = fmt.Fprintf(f, "P3\n%d %d\n255\n", nx, ny)

	check(err, "Error writting to file: %v\n")

	// writes each pixel with r/g/b values
	// from top left to bottom right
	for j := ny - 1; j >= 0; j-- {
		for i := 0; i < nx; i++ {
			// red and green values range from
			// 0.0 to 1.0
			v := Vector{X: float64(i) / float64(nx), Y: float64(j) / float64(ny), Z: 0.2}

			// get intensity of colors
			ir := int(color * v.X)
			ig := int(color * v.Y)
			ib := int(color * v.Z)

			_, err = fmt.Fprintf(f, "%d %d %d\n", ir, ig, ib)

			check(err, "Error writing to file: %v\n")
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/codedeploy"
	"github.com/drone/drone-go/drone"
	"github.com/drone/drone-go/plugin"
)

var (
	build     string
	buildDate string
)

func main() {
	fmt.Printf("Drone CodeDeply Plugin built at %s\n", buildDate)

	repo := drone.Repo{}
	build := drone.Build{}
	vargs := Params{}

	plugin.Param("repo", &repo)
	plugin.Param("build", &build)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()

	if vargs.Application == "" {
		vargs.Application = repo.Name
	}

	if vargs.RevisionType == "" {
		vargs.RevisionType = codedeploy.RevisionLocationTypeGitHub
	}

	if vargs.AccessKey == "" {
		fmt.Println("Please provide an access key id")
		os.Exit(1)
	}

	if vargs.SecretKey == "" {
		fmt.Println("Please provide a secret access key")
		os.Exit(1)
	}

	if vargs.Region == "" {
		fmt.Println("Please provide a region")
		os.Exit(1)
	}

	if vargs.DeploymentGroup == "" {
		fmt.Println("Please provide a deployment group")
		os.Exit(1)
	}

	switch vargs.RevisionType {
	case codedeploy.RevisionLocationTypeGitHub:
	case codedeploy.RevisionLocationTypeS3:
		if vargs.BundleType == "" {
			fmt.Println("Please provide a bundle type")
			os.Exit(1)
		}

		if vargs.BucketName == "" {
			fmt.Println("Please provide a bucket name")
			os.Exit(1)
		}

		if vargs.BucketKey == "" {
			fmt.Println("Please provide a bucket key")
			os.Exit(1)
		}

		switch vargs.BundleType {
		case codedeploy.BundleTypeTar:
		case codedeploy.BundleTypeTgz:
		case codedeploy.BundleTypeZip:
		default:
			fmt.Println("Invalid bundle type")
			os.Exit(1)
		}
	default:
		fmt.Println("Invalid revision type")
		os.Exit(1)
	}

	svc := codedeploy.New(
		session.New(&aws.Config{
			Region:      aws.String(vargs.Region),
			Credentials: credentials.NewStaticCredentials(
				vargs.AccessKey,
				vargs.SecretKey,
				"",
			),
		}),
	)

	_, err := svc.CreateDeployment(
		&codedeploy.CreateDeploymentInput{
			ApplicationName:               aws.String(vargs.Application),
			DeploymentConfigName:          aws.String(vargs.DeploymentConfig),
			DeploymentGroupName:           aws.String(vargs.DeploymentGroup),
			Description:                   aws.String(vargs.Description),
			IgnoreApplicationStopFailures: aws.Bool(vargs.IgnoreStopFailures),
			Revision: &codedeploy.RevisionLocation{
				RevisionType: aws.String(vargs.RevisionType),
				GitHubLocation: &codedeploy.GitHubLocation{
					CommitId:   aws.String(build.Commit),
					Repository: aws.String(repo.FullName),
				},
				S3Location: &codedeploy.S3Location{
					BundleType: aws.String(vargs.BundleType),
					Bucket:     aws.String(vargs.BucketName),
					Key:        aws.String(vargs.BucketKey),
					ETag:       aws.String(vargs.BucketEtag),
					Version:    aws.String(vargs.BucketVersion),
				},
			},
		},
	)

	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	fmt.Println("Successfully deployed")
}
<commit_msg>Assign only one revision location<commit_after>package main

import (
	"fmt"
	"os"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/codedeploy"
	"github.com/drone/drone-go/drone"
	"github.com/drone/drone-go/plugin"
)

var (
	build     string
	buildDate string
)

func main() {
	fmt.Printf("Drone CodeDeply Plugin built at %s\n", buildDate)

	repo := drone.Repo{}
	build := drone.Build{}
	vargs := Params{}

	plugin.Param("repo", &repo)
	plugin.Param("build", &build)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()

	if vargs.Application == "" {
		vargs.Application = repo.Name
	}

	if vargs.RevisionType == "" {
		vargs.RevisionType = codedeploy.RevisionLocationTypeGitHub
	}

	if vargs.AccessKey == "" {
		fmt.Println("Please provide an access key id")
		os.Exit(1)
	}

	if vargs.SecretKey == "" {
		fmt.Println("Please provide a secret access key")
		os.Exit(1)
	}

	if vargs.Region == "" {
		fmt.Println("Please provide a region")
		os.Exit(1)
	}

	if vargs.DeploymentGroup == "" {
		fmt.Println("Please provide a deployment group")
		os.Exit(1)
	}

	var location *codedeploy.RevisionLocation

	switch vargs.RevisionType {
	case codedeploy.RevisionLocationTypeGitHub:
		location = &codedeploy.RevisionLocation{
			RevisionType: aws.String(vargs.RevisionType),
			GitHubLocation: &codedeploy.GitHubLocation{
				CommitId:   aws.String(build.Commit),
				Repository: aws.String(repo.FullName),
			},
		}
	case codedeploy.RevisionLocationTypeS3:
		if vargs.BundleType == "" {
			fmt.Println("Please provide a bundle type")
			os.Exit(1)
		}

		if vargs.BucketName == "" {
			fmt.Println("Please provide a bucket name")
			os.Exit(1)
		}

		if vargs.BucketKey == "" {
			fmt.Println("Please provide a bucket key")
			os.Exit(1)
		}

		switch vargs.BundleType {
		case codedeploy.BundleTypeTar:
		case codedeploy.BundleTypeTgz:
		case codedeploy.BundleTypeZip:
		default:
			fmt.Println("Invalid bundle type")
			os.Exit(1)
		}

		location = &codedeploy.RevisionLocation{
			RevisionType: aws.String(vargs.RevisionType),
			S3Location: &codedeploy.S3Location{
				BundleType: aws.String(vargs.BundleType),
				Bucket:     aws.String(vargs.BucketName),
				Key:        aws.String(vargs.BucketKey),
				ETag:       aws.String(vargs.BucketEtag),
				Version:    aws.String(vargs.BucketVersion),
			},
		}
	default:
		fmt.Println("Invalid revision type")
		os.Exit(1)
	}

	svc := codedeploy.New(
		session.New(&aws.Config{
			Region: aws.String(vargs.Region),
			Credentials: credentials.NewStaticCredentials(
				vargs.AccessKey,
				vargs.SecretKey,
				"",
			),
		}),
	)

	_, err := svc.CreateDeployment(
		&codedeploy.CreateDeploymentInput{
			ApplicationName:               aws.String(vargs.Application),
			DeploymentConfigName:          aws.String(vargs.DeploymentConfig),
			DeploymentGroupName:           aws.String(vargs.DeploymentGroup),
			Description:                   aws.String(vargs.Description),
			IgnoreApplicationStopFailures: aws.Bool(vargs.IgnoreStopFailures),
			Revision:                      location,
		},
	)

	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	fmt.Println("Successfully deployed")
}
<|endoftext|>


<commit_before>package main

import (
	"runtime"

	"fmt"

	"github.com/getfider/fider/app/models"
	"github.com/getfider/fider/app/pkg/env"
	_ "github.com/lib/pq"
	_ "github.com/mattes/migrate/database/postgres"
	_ "github.com/mattes/migrate/source/file"
)

var buildtime string
var version = "0.12.0-beta"

func main() {
	fmt.Printf("Application is starting...\n")
	fmt.Printf("GO_ENV: %s\n", env.Current())

	settings := &models.SystemSettings{
		BuildTime:       buildtime,
		Version:         version,
		Compiler:        runtime.Version(),
		Environment:     env.Current(),
		GoogleAnalytics: env.GetEnvOrDefault("GOOGLE_ANALYTICS", ""),
		Mode:            env.Mode(),
		Domain:          env.MultiTenantDomain(),
	}

	e := GetMainEngine(settings)
	e.Start(":" + env.GetEnvOrDefault("PORT", "3000"))
}
<commit_msg>chore: bump version to 0.12.0 (#360)<commit_after>package main

import (
	"runtime"

	"fmt"

	"github.com/getfider/fider/app/models"
	"github.com/getfider/fider/app/pkg/env"
	_ "github.com/lib/pq"
	_ "github.com/mattes/migrate/database/postgres"
	_ "github.com/mattes/migrate/source/file"
)

var buildtime string
var version = "0.12.0"

func main() {
	fmt.Printf("Application is starting...\n")
	fmt.Printf("GO_ENV: %s\n", env.Current())

	settings := &models.SystemSettings{
		BuildTime:       buildtime,
		Version:         version,
		Compiler:        runtime.Version(),
		Environment:     env.Current(),
		GoogleAnalytics: env.GetEnvOrDefault("GOOGLE_ANALYTICS", ""),
		Mode:            env.Mode(),
		Domain:          env.MultiTenantDomain(),
	}

	e := GetMainEngine(settings)
	e.Start(":" + env.GetEnvOrDefault("PORT", "3000"))
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"os/user"
	"strconv"
	"strings"
)

func main() {
	// Get our user and group list
	un := os.Getenv("USER")
	if un == "" {
		os.Exit(3)
	}
	gl := strings.Split(os.Getenv("GROUP"), " ")
	if len(gl) < 1 {
		os.Exit(4)
	}

	// Get user struct, primary gid, and gid (string) array
	u, err := user.Lookup(un)
	if err != nil {
		os.Exit(2)
	}
	gid, err := strconv.ParseInt(u.Gid, 10, 64)
	if err != nil {
		os.Exit(2)
	}
	gs, err := u.GroupIds()
	if err != nil {
		os.Exit(2)
	}

	// Convert gid strings to gid ints
	var gids []int64
	for _, v := range gs {
		g, err := strconv.ParseInt(v, 10, 64)
		if err == nil {
			gids = append(gids, g)
		}
	}

	// Check each of the supplied group names/gids
	for _, v := range gl {
		ggid, err := strconv.ParseInt(v, 10, 64)
		if err == nil {
			// Group is a gid
			if ggid == gid {
				// gid matches primary group
				os.Exit(0)
			} else {
				for _, v := range gids {
					if ggid == v {
						// gid matches secondary group
						os.Exit(0)
					}
				}
			}
		} else {
			// Group is a group name
			fmt.Printf("v: %s\n", v)
			g, err := user.LookupGroup(v)
			if err != nil {
				// Group is invalid
				continue
			}
			ggid, err := strconv.ParseInt(g.Gid, 10, 64)
			if err != nil {
				// Group doesn't exist or gid isn't numeric
				continue
			}

			if ggid == gid {
				// gid matches primary group
				os.Exit(0)
			} else {
				for _, v := range gids {
					if ggid == v {
						// gid matches secondary group
						os.Exit(0)
					}
				}
			}
		}
	}

	os.Exit(1)
}
<commit_msg>Switched from space-separated to comma-separated group list<commit_after>package main

import (
	"fmt"
	"os"
	"os/user"
	"strconv"
	"strings"
)

func main() {
	// Get our user and group list
	un := os.Getenv("USER")
	if un == "" {
		os.Exit(3)
	}
	gl := strings.Split(os.Getenv("GROUP"), ",")
	if len(gl) < 1 {
		os.Exit(4)
	}

	// Get user struct, primary gid, and gid (string) array
	u, err := user.Lookup(un)
	if err != nil {
		os.Exit(2)
	}
	gid, err := strconv.ParseInt(u.Gid, 10, 64)
	if err != nil {
		os.Exit(2)
	}
	gs, err := u.GroupIds()
	if err != nil {
		os.Exit(2)
	}

	// Convert gid strings to gid ints
	var gids []int64
	for _, v := range gs {
		g, err := strconv.ParseInt(v, 10, 64)
		if err == nil {
			gids = append(gids, g)
		}
	}

	// Check each of the supplied group names/gids
	for _, v := range gl {
		ggid, err := strconv.ParseInt(v, 10, 64)
		if err == nil {
			// Group is a gid
			if ggid == gid {
				// gid matches primary group
				os.Exit(0)
			} else {
				for _, v := range gids {
					if ggid == v {
						// gid matches secondary group
						os.Exit(0)
					}
				}
			}
		} else {
			// Group is a group name
			fmt.Printf("v: %s\n", v)
			g, err := user.LookupGroup(v)
			if err != nil {
				// Group is invalid
				continue
			}
			ggid, err := strconv.ParseInt(g.Gid, 10, 64)
			if err != nil {
				// Group doesn't exist or gid isn't numeric
				continue
			}

			if ggid == gid {
				// gid matches primary group
				os.Exit(0)
			} else {
				for _, v := range gids {
					if ggid == v {
						// gid matches secondary group
						os.Exit(0)
					}
				}
			}
		}
	}

	os.Exit(1)
}
<|endoftext|>


<commit_before>package main

import (
  "fmt"
  "time"
  "os"
  "bufio"
  "log"
  "regexp"
  "errors"
  "math/rand"
)

type Posicao struct {
  linha  int
  coluna int
}

type PacGo struct {
  posicao    Posicao
  figura     string // emoji
  pilula     bool
  vidas      int
  pontos     int
  invencivel bool
  figuras []string
  indiceFig int
  figuraBravo string
  contadorFig Contador
}

type Contador struct {
  max       int
  contador  int
}

type Fantasma struct {
  posicao Posicao
  figura  string // emoji
}

type Labirinto struct {
  largura       int
  altura        int
  mapa          []string
  figMuro       string
  figMuroSuper  string
  figSP         string
  quantiaPastilhas int
}

type Movimento int

const (
  Cima = iota
  Baixo
  Esquerda
  Direita
  Nenhum
  Sai
)

var labirinto  *Labirinto
var pacgo      *PacGo
var fantasmas  []*Fantasma
var mapaSinais map[int]string

func criarFantasma(posicao Posicao, figura string) {
  fantasma := &Fantasma{ posicao:posicao, figura: figura}
  fantasmas = append(fantasmas, fantasma)
}

func criarPacGo(posicao Posicao, figura string, pilula bool, vidas int) {
  pacgo = &PacGo{ posicao:posicao, figura: "\xF0\x9F\x98\x83", pilula: false, vidas:3 ,
    figuras: []string {"\xF0\x9F\x98\x83", "\xF0\x9F\x98\x8C"}, indiceFig : 0 , contadorFig: Contador{3, 0},
    figuraBravo: "\xF0\x9F\x98\xA1"}
}

func construirLabirinto(nomeArquivo string) error {

  var ErrMapNotFound = errors.New("Não conseguiu ler o arquivo do mapa")

  var arquivo string
  if nomeArquivo == "" {
    arquivo = "./data/mapa.txt"
  } else {
    arquivo = nomeArquivo
  }

  if file, err := os.Open(arquivo); err == nil {

    // fecha depois de ler o arquivo
    defer file.Close()

    // inicializa o mapa vazio
    mapa := []string{}

    r, _ := regexp.Compile("[^ #.P]")

    // cria um leitor para ler linha a linha o arquivo
    scanner := bufio.NewScanner(file)
    quantiaPastilhas := 0
    for scanner.Scan() {
      linha := scanner.Text()

      for indice , caracter := range linha {
        switch caracter {
          case 'F': criarFantasma( Posicao{len(mapa), indice}, "\xF0\x9F\x91\xBB" )
          case 'G': criarPacGo( Posicao{len(mapa), indice}, "\xF0\x9F\x98\x83", false, 3 )
          case '.': quantiaPastilhas += 1
        }
      }

      linha = r.ReplaceAllString(linha, " ")
      mapa = append(mapa, linha)
    }

    // verifica se teve erro o leitor
    if err = scanner.Err(); err != nil {
      log.Fatal(err)
      return ErrMapNotFound
    }

    labirinto = &Labirinto{
      largura: len(mapa[0]),
      altura: len(mapa),
      mapa: mapa,
      figMuro: "\x1b[44m \x1b[0m",
      figMuroSuper: "\x1b[41m \x1b[0m",
      figSP: "\xF0\x9F\x8D\x84",
      quantiaPastilhas: quantiaPastilhas,
    }
    return nil

  } else {
    log.Fatal(err)
    return ErrMapNotFound
  }
}

func atualizarLabirinto() {
  tela.limpa()

  // Imprime os pontos
  tela.moveCursor(Posicao{0,0})
  fmt.Printf("%sPontos: %d Vidas: %d%s\n", "\x1b[31;1m", pacgo.pontos, pacgo.vidas, "\x1b[0m")

  posicaoInicial := Posicao{2,0}
  tela.moveCursor(posicaoInicial)

  var muro = labirinto.figMuro
  if pacgo.pilula == true{
    muro = labirinto.figMuroSuper
  }

  for _, linha := range labirinto.mapa {
    for _, char := range linha {
      switch char {
        case '#': fmt.Print(muro)
        case '.': fmt.Print(".")
        case 'P': fmt.Print(labirinto.figSP)
        default:  fmt.Print(" ")
      }
    }
    fmt.Println("")
  }

  // Imprime PacGo
  tela.moveCursor(posicaoInicial.adiciona(&pacgo.posicao))
  if (pacgo.pilula) {
    fmt.Printf("%s", pacgo.figuraBravo)
  } else {
    fmt.Printf("%s", pacgo.figuras[pacgo.indiceFig])
    pacgo.incrementaIndice()
  }

  // Imprime fantasmas
  for _, fantasma := range fantasmas {
    tela.moveCursor(posicaoInicial.adiciona(&fantasma.posicao))
    fmt.Printf("%s", fantasma.figura)
  }

  // Move o cursor para fora do labirinto
  tela.moveCursor(posicaoInicial.adiciona(&Posicao{labirinto.altura + 2, 0}))
}

func detectarColisao() bool {
  for _, fantasma := range fantasmas {
    if fantasma.posicao == pacgo.posicao {
      return true
    }
  }
  return false
}

func moverPacGo(m Movimento) {
  var novaLinha = pacgo.posicao.linha
  var novaColuna = pacgo.posicao.coluna

  switch m {
    case Cima:
      novaLinha--
      if novaLinha < 0 {
        novaLinha = labirinto.altura - 1
      }
    case Baixo:
      novaLinha++
      if novaLinha >= labirinto.altura {
        novaLinha = 0
      }
    case Direita:
      novaColuna++
      if novaColuna >= labirinto.largura {
        novaColuna = 0
      }
    case Esquerda:
      novaColuna--
      if novaColuna < 0 {
        novaColuna = labirinto.largura - 1
      }
  }

  conteudoDoMapa := labirinto.mapa[novaLinha][novaColuna]
  if conteudoDoMapa != '#' {
    pacgo.posicao.linha = novaLinha
    pacgo.posicao.coluna = novaColuna

    if (conteudoDoMapa == '.') || (conteudoDoMapa == 'P') {
      if (conteudoDoMapa == '.') {
        pacgo.pontos += 10
        fmt.Print("\x07")
        labirinto.quantiaPastilhas--
      } else {
        pacgo.pontos += 100
        ativarPilula()
      }

      linha := labirinto.mapa[novaLinha]
      linha = linha[:novaColuna] + " " + linha[novaColuna+1:]
      labirinto.mapa[novaLinha] = linha
    }
  }
}

func random(min, max int) int {
    return rand.Intn(max - min) + min
}

func move(fantasma *Fantasma, valorDaPosicaoAtualDoFantasma byte, linhaAtualDoFantasma int, colunaAtualDoFantasma int){

  var direcao = random(0, 4)
  var sinal = mapaSinais[direcao]
  //fmt.Println(sinal)
  switch sinal {
  case "Cima":
              if linhaAtualDoFantasma == 0{
                if valorDaPosicaoAtualDoFantasma == ' '{
                   fantasma.posicao.linha = labirinto.altura - 1
                 }
             }else{
               var posicaoAcimaDoFantasma = labirinto.mapa[fantasma.posicao.linha - 1][fantasma.posicao.coluna]
               if posicaoAcimaDoFantasma != '#'{
                 fantasma.posicao.linha = fantasma.posicao.linha - 1
               }
             }
  case "Baixo":
              if linhaAtualDoFantasma == labirinto.altura - 1{
                 if valorDaPosicaoAtualDoFantasma == ' '{
                   fantasma.posicao.linha = 0
                 }
              }else{
                var posicaoAbaixoDoFantasma = labirinto.mapa[fantasma.posicao.linha + 1][fantasma.posicao.coluna]
                if posicaoAbaixoDoFantasma != '#'{
                  fantasma.posicao.linha = fantasma.posicao.linha + 1
                }
              }
  case "Direita":
                if colunaAtualDoFantasma == labirinto.largura-1{
                  if valorDaPosicaoAtualDoFantasma == ' '{
                    fantasma.posicao.coluna = 0
                  }
                }else{
                  var posicaoDireitaDofantasma = labirinto.mapa[fantasma.posicao.linha][fantasma.posicao.coluna + 1]
                  if posicaoDireitaDofantasma != '#'{
                    fantasma.posicao.coluna = fantasma.posicao.coluna + 1
                  }
                }
  case "Esquerda":
                 if colunaAtualDoFantasma == 0{
                   if valorDaPosicaoAtualDoFantasma == ' '{
                     fantasma.posicao.coluna = labirinto.largura - 1
                   }
                 }else{
                   var posicaoEsquerdaDoFantasma = labirinto.mapa[fantasma.posicao.linha][fantasma.posicao.coluna - 1]
                   if posicaoEsquerdaDoFantasma != '#'{
                     fantasma.posicao.coluna = fantasma.posicao.coluna - 1
                   }
                 }
  }
}

func moverFantasmas() {

  for {
    for i := 0; i < len(fantasmas); i++{
        var valorDaPosicaoAtualDoFantasma = labirinto.mapa[fantasmas[i].posicao.linha][fantasmas[i].posicao.coluna]
        var linhaAtualDoFantasma = fantasmas[i].posicao.linha
        var colunaAtualDoFantasma = fantasmas[i].posicao.coluna
        //fmt.Println(valorDaPosicaoAtualDoFantasma, linhaAtualDoFantasma, colunaAtualDoFantasma)
        move(fantasmas[i], valorDaPosicaoAtualDoFantasma, linhaAtualDoFantasma, colunaAtualDoFantasma)
    }
    dorme(300)
  }
}

func dorme(milisegundos time.Duration) {
  time.Sleep(time.Millisecond * milisegundos)
}

func entradaDoUsuario(canal chan<- Movimento) {
  array := make([]byte, 10)

  for {
    lido, _ := os.Stdin.Read(array)

    if lido == 1 && array[0] == 0x1b {
      canal <- Sai;
    } else if lido == 3 {
      if array[0] == 0x1b && array[1] == '[' {
        switch array[2] {
          case 'A': canal <- Cima
          case 'B': canal <- Baixo
          case 'C': canal <- Direita
          case 'D': canal <- Esquerda
        }
      }
    }
  }
}

func ativarPilula() {
  pacgo.pilula = true
  go desativarPilula(10000)
}

func desativarPilula(milisegundos time.Duration) {
  dorme(milisegundos)
  pacgo.pilula = false
}

func terminarJogo() {
  // pacgo morreu :(
  tela.moveCursor( Posicao{labirinto.altura + 2, 0} )
  fmt.Println("Fim de jogo! Os fantasmas venceram... \xF0\x9F\x98\xAD")
}

func main() {
  inicializa()
  defer finaliza()

  mapaSinais = make(map[int]string)
  mapaSinais[0] = "Cima"
  mapaSinais[1] = "Baixo"
  mapaSinais[2] = "Direita"
  mapaSinais[3] = "Esquerda"

  args    := os.Args[1:]
  var arquivo string
  if len(args) >= 1 {
    arquivo = args[0]
  } else {
    arquivo = ""
  }

  construirLabirinto(arquivo)

  canal := make(chan Movimento, 10)

  // Processos assincronos
  go entradaDoUsuario(canal)
  go moverFantasmas()

  var tecla Movimento
  for {
    atualizarLabirinto()
    if labirinto.quantiaPastilhas == 0 {
      tela.moveCursor( Posicao{labirinto.altura + 2, 0} )
      fmt.Println("Fim de jogo! Você venceu! \xF0\x9F\x98\x84")
      break
    }

    // canal não-bloqueador
    select {
      case tecla = <-canal:
        moverPacGo(tecla)
      default:
    }
    if tecla == Sai { break }

    if detectarColisao() {
      if pacgo.pilula {
        _, f := buscaFantasma(pacgo.posicao)
        go criarFantasmaTemporizado(f, 5000)
        matarFantasma(f)
        pacgo.pontos = pacgo.pontos + 500
      } else {
        // pacgo perde vidas
        if !pacgo.invencivel {
          pacgo.vidas--
          if pacgo.vidas < 0 {
            terminarJogo()
            break
          }
          ativarInvencibilidade(3000)
        }
      }
    }

    dorme(100)
  }
}

func ativarInvencibilidade(milisegundos time.Duration) {
  pacgo.invencivel = true
  go func() {
    dorme(milisegundos)
    pacgo.invencivel = false
  }()
}

func buscaFantasma(posicao Posicao) (int, *Fantasma) {
  for i, fantasma := range fantasmas {
    if fantasma.posicao == posicao {
      return i, fantasma
    }
  }
  return -1, nil
}

func criarFantasmaTemporizado(fantasma *Fantasma, milisegundos time.Duration) {
  dorme(milisegundos)
  criarFantasma(fantasma.posicao, fantasma.figura)
}

func matarFantasma(fantasma *Fantasma) {
  pos, _ := buscaFantasma(fantasma.posicao)
  fantasmas = append(fantasmas[:pos], fantasmas[pos+1:]...)
  fmt.Print("\x07")
}
<commit_msg>Volta para a posição inicial quando morre<commit_after>package main

import (
  "fmt"
  "time"
  "os"
  "bufio"
  "log"
  "regexp"
  "errors"
  "math/rand"
)

type Posicao struct {
  linha  int
  coluna int
}

type PacGo struct {
  posicao    Posicao
  posicaoInicial Posicao
  figura     string // emoji
  pilula     bool
  vidas      int
  pontos     int
  invencivel bool
  figuras []string
  indiceFig int
  figuraBravo string
  contadorFig Contador
}

type Contador struct {
  max       int
  contador  int
}

type Fantasma struct {
  posicao Posicao
  figura  string // emoji
}

type Labirinto struct {
  largura       int
  altura        int
  mapa          []string
  figMuro       string
  figMuroSuper  string
  figSP         string
  quantiaPastilhas int
}

type Movimento int

const (
  Cima = iota
  Baixo
  Esquerda
  Direita
  Nenhum
  Sai
)

var labirinto  *Labirinto
var pacgo      *PacGo
var fantasmas  []*Fantasma
var mapaSinais map[int]string

func criarFantasma(posicao Posicao, figura string) {
  fantasma := &Fantasma{ posicao:posicao, figura: figura}
  fantasmas = append(fantasmas, fantasma)
}

func criarPacGo(posicao Posicao, figura string, pilula bool, vidas int) {
  pacgo = &PacGo{
    posicao: posicao,
    posicaoInicial: posicao,
    figura: "\xF0\x9F\x98\x83",
    pilula: false,
    vidas: 3,
    figuras: []string {"\xF0\x9F\x98\x83", "\xF0\x9F\x98\x8C"},
    indiceFig: 0 ,
    contadorFig: Contador{3, 0},
    figuraBravo: "\xF0\x9F\x98\xA1",
  }
}

func construirLabirinto(nomeArquivo string) error {

  var ErrMapNotFound = errors.New("Não conseguiu ler o arquivo do mapa")

  var arquivo string
  if nomeArquivo == "" {
    arquivo = "./data/mapa.txt"
  } else {
    arquivo = nomeArquivo
  }

  if file, err := os.Open(arquivo); err == nil {

    // fecha depois de ler o arquivo
    defer file.Close()

    // inicializa o mapa vazio
    mapa := []string{}

    r, _ := regexp.Compile("[^ #.P]")

    // cria um leitor para ler linha a linha o arquivo
    scanner := bufio.NewScanner(file)
    quantiaPastilhas := 0
    for scanner.Scan() {
      linha := scanner.Text()

      for indice , caracter := range linha {
        switch caracter {
          case 'F': criarFantasma( Posicao{len(mapa), indice}, "\xF0\x9F\x91\xBB" )
          case 'G': criarPacGo( Posicao{len(mapa), indice}, "\xF0\x9F\x98\x83", false, 3 )
          case '.': quantiaPastilhas += 1
        }
      }

      linha = r.ReplaceAllString(linha, " ")
      mapa = append(mapa, linha)
    }

    // verifica se teve erro o leitor
    if err = scanner.Err(); err != nil {
      log.Fatal(err)
      return ErrMapNotFound
    }

    labirinto = &Labirinto{
      largura: len(mapa[0]),
      altura: len(mapa),
      mapa: mapa,
      figMuro: "\x1b[44m \x1b[0m",
      figMuroSuper: "\x1b[41m \x1b[0m",
      figSP: "\xF0\x9F\x8D\x84",
      quantiaPastilhas: quantiaPastilhas,
    }
    return nil

  } else {
    log.Fatal(err)
    return ErrMapNotFound
  }
}

func atualizarLabirinto() {
  tela.limpa()

  // Imprime os pontos
  tela.moveCursor(Posicao{0,0})
  fmt.Printf("%sPontos: %d Vidas: %d%s\n", "\x1b[31;1m", pacgo.pontos, pacgo.vidas, "\x1b[0m")

  posicaoInicial := Posicao{2,0}
  tela.moveCursor(posicaoInicial)

  var muro = labirinto.figMuro
  if pacgo.pilula == true{
    muro = labirinto.figMuroSuper
  }

  for _, linha := range labirinto.mapa {
    for _, char := range linha {
      switch char {
        case '#': fmt.Print(muro)
        case '.': fmt.Print(".")
        case 'P': fmt.Print(labirinto.figSP)
        default:  fmt.Print(" ")
      }
    }
    fmt.Println("")
  }

  // Imprime PacGo
  tela.moveCursor(posicaoInicial.adiciona(&pacgo.posicao))
  if (pacgo.pilula) {
    fmt.Printf("%s", pacgo.figuraBravo)
  } else {
    fmt.Printf("%s", pacgo.figuras[pacgo.indiceFig])
    pacgo.incrementaIndice()
  }

  // Imprime fantasmas
  for _, fantasma := range fantasmas {
    tela.moveCursor(posicaoInicial.adiciona(&fantasma.posicao))
    fmt.Printf("%s", fantasma.figura)
  }

  // Move o cursor para fora do labirinto
  tela.moveCursor(posicaoInicial.adiciona(&Posicao{labirinto.altura + 2, 0}))
}

func detectarColisao() bool {
  for _, fantasma := range fantasmas {
    if fantasma.posicao == pacgo.posicao {
      return true
    }
  }
  return false
}

func moverPacGo(m Movimento) {
  var novaLinha = pacgo.posicao.linha
  var novaColuna = pacgo.posicao.coluna

  switch m {
    case Cima:
      novaLinha--
      if novaLinha < 0 {
        novaLinha = labirinto.altura - 1
      }
    case Baixo:
      novaLinha++
      if novaLinha >= labirinto.altura {
        novaLinha = 0
      }
    case Direita:
      novaColuna++
      if novaColuna >= labirinto.largura {
        novaColuna = 0
      }
    case Esquerda:
      novaColuna--
      if novaColuna < 0 {
        novaColuna = labirinto.largura - 1
      }
  }

  conteudoDoMapa := labirinto.mapa[novaLinha][novaColuna]
  if conteudoDoMapa != '#' {
    pacgo.posicao.linha = novaLinha
    pacgo.posicao.coluna = novaColuna

    if (conteudoDoMapa == '.') || (conteudoDoMapa == 'P') {
      if (conteudoDoMapa == '.') {
        pacgo.pontos += 10
        fmt.Print("\x07")
        labirinto.quantiaPastilhas--
      } else {
        pacgo.pontos += 100
        ativarPilula()
      }

      linha := labirinto.mapa[novaLinha]
      linha = linha[:novaColuna] + " " + linha[novaColuna+1:]
      labirinto.mapa[novaLinha] = linha
    }
  }
}

func random(min, max int) int {
    return rand.Intn(max - min) + min
}

func move(fantasma *Fantasma, valorDaPosicaoAtualDoFantasma byte, linhaAtualDoFantasma int, colunaAtualDoFantasma int){

  var direcao = random(0, 4)
  var sinal = mapaSinais[direcao]
  //fmt.Println(sinal)
  switch sinal {
  case "Cima":
              if linhaAtualDoFantasma == 0{
                if valorDaPosicaoAtualDoFantasma == ' '{
                   fantasma.posicao.linha = labirinto.altura - 1
                 }
             }else{
               var posicaoAcimaDoFantasma = labirinto.mapa[fantasma.posicao.linha - 1][fantasma.posicao.coluna]
               if posicaoAcimaDoFantasma != '#'{
                 fantasma.posicao.linha = fantasma.posicao.linha - 1
               }
             }
  case "Baixo":
              if linhaAtualDoFantasma == labirinto.altura - 1{
                 if valorDaPosicaoAtualDoFantasma == ' '{
                   fantasma.posicao.linha = 0
                 }
              }else{
                var posicaoAbaixoDoFantasma = labirinto.mapa[fantasma.posicao.linha + 1][fantasma.posicao.coluna]
                if posicaoAbaixoDoFantasma != '#'{
                  fantasma.posicao.linha = fantasma.posicao.linha + 1
                }
              }
  case "Direita":
                if colunaAtualDoFantasma == labirinto.largura-1{
                  if valorDaPosicaoAtualDoFantasma == ' '{
                    fantasma.posicao.coluna = 0
                  }
                }else{
                  var posicaoDireitaDofantasma = labirinto.mapa[fantasma.posicao.linha][fantasma.posicao.coluna + 1]
                  if posicaoDireitaDofantasma != '#'{
                    fantasma.posicao.coluna = fantasma.posicao.coluna + 1
                  }
                }
  case "Esquerda":
                 if colunaAtualDoFantasma == 0{
                   if valorDaPosicaoAtualDoFantasma == ' '{
                     fantasma.posicao.coluna = labirinto.largura - 1
                   }
                 }else{
                   var posicaoEsquerdaDoFantasma = labirinto.mapa[fantasma.posicao.linha][fantasma.posicao.coluna - 1]
                   if posicaoEsquerdaDoFantasma != '#'{
                     fantasma.posicao.coluna = fantasma.posicao.coluna - 1
                   }
                 }
  }
}

func moverFantasmas() {

  for {
    for i := 0; i < len(fantasmas); i++{
        var valorDaPosicaoAtualDoFantasma = labirinto.mapa[fantasmas[i].posicao.linha][fantasmas[i].posicao.coluna]
        var linhaAtualDoFantasma = fantasmas[i].posicao.linha
        var colunaAtualDoFantasma = fantasmas[i].posicao.coluna
        //fmt.Println(valorDaPosicaoAtualDoFantasma, linhaAtualDoFantasma, colunaAtualDoFantasma)
        move(fantasmas[i], valorDaPosicaoAtualDoFantasma, linhaAtualDoFantasma, colunaAtualDoFantasma)
    }
    dorme(300)
  }
}

func dorme(milisegundos time.Duration) {
  time.Sleep(time.Millisecond * milisegundos)
}

func entradaDoUsuario(canal chan<- Movimento) {
  array := make([]byte, 10)

  for {
    lido, _ := os.Stdin.Read(array)

    if lido == 1 && array[0] == 0x1b {
      canal <- Sai;
    } else if lido == 3 {
      if array[0] == 0x1b && array[1] == '[' {
        switch array[2] {
          case 'A': canal <- Cima
          case 'B': canal <- Baixo
          case 'C': canal <- Direita
          case 'D': canal <- Esquerda
        }
      }
    }
  }
}

func ativarPilula() {
  pacgo.pilula = true
  go desativarPilula(10000)
}

func desativarPilula(milisegundos time.Duration) {
  dorme(milisegundos)
  pacgo.pilula = false
}

func terminarJogo() {
  // pacgo morreu :(
  tela.moveCursor( Posicao{labirinto.altura + 2, 0} )
  fmt.Println("Fim de jogo! Os fantasmas venceram... \xF0\x9F\x98\xAD")
}

func main() {
  inicializa()
  defer finaliza()

  mapaSinais = make(map[int]string)
  mapaSinais[0] = "Cima"
  mapaSinais[1] = "Baixo"
  mapaSinais[2] = "Direita"
  mapaSinais[3] = "Esquerda"

  args    := os.Args[1:]
  var arquivo string
  if len(args) >= 1 {
    arquivo = args[0]
  } else {
    arquivo = ""
  }

  construirLabirinto(arquivo)

  canal := make(chan Movimento, 10)

  // Processos assincronos
  go entradaDoUsuario(canal)
  go moverFantasmas()

  var tecla Movimento
  for {
    atualizarLabirinto()
    if labirinto.quantiaPastilhas == 0 {
      tela.moveCursor( Posicao{labirinto.altura + 2, 0} )
      fmt.Println("Fim de jogo! Você venceu! \xF0\x9F\x98\x84")
      break
    }

    // canal não-bloqueador
    select {
      case tecla = <-canal:
        moverPacGo(tecla)
      default:
    }
    if tecla == Sai { break }

    if detectarColisao() {
      if pacgo.pilula {
        _, f := buscaFantasma(pacgo.posicao)
        go criarFantasmaTemporizado(f, 5000)
        matarFantasma(f)
        pacgo.pontos = pacgo.pontos + 500
      } else {
        // pacgo perde vidas
        if !pacgo.invencivel {
          pacgo.vidas--
          if pacgo.vidas < 0 {
            terminarJogo()
            break
          }
          ativarInvencibilidade(3000)
          pacgo.posicao.linha = pacgo.posicaoInicial.linha
          pacgo.posicao.coluna = pacgo.posicaoInicial.coluna
        }
      }
    }

    dorme(100)
  }
}

func ativarInvencibilidade(milisegundos time.Duration) {
  pacgo.invencivel = true
  go func() {
    dorme(milisegundos)
    pacgo.invencivel = false
  }()
}

func buscaFantasma(posicao Posicao) (int, *Fantasma) {
  for i, fantasma := range fantasmas {
    if fantasma.posicao == posicao {
      return i, fantasma
    }
  }
  return -1, nil
}

func criarFantasmaTemporizado(fantasma *Fantasma, milisegundos time.Duration) {
  dorme(milisegundos)
  criarFantasma(fantasma.posicao, fantasma.figura)
}

func matarFantasma(fantasma *Fantasma) {
  pos, _ := buscaFantasma(fantasma.posicao)
  fantasmas = append(fantasmas[:pos], fantasmas[pos+1:]...)
  fmt.Print("\x07")
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"path/filepath"
)

const (
	distRoot = "dist"
)

var (
	gooses   = &[]string{"windows", "linux"}
	goarches = &[]string{"amd64", "386"}
	name     = currentFolderName()
	version  = gitVersion()
)

func main() {
	goGenerate()

	for _, goos := range *gooses {
		for _, goarch := range *goarches {
			buildName := name + "-" + version + "-" + goos + "-" + goarch

			fmt.Println("Building " + buildName + "...")
			goBuild(goos, goarch, buildName)
		}
	}
}

func panicIf(err error) {
	if err != nil {
		panic(err.Error())
	}
}

// currentFolderName returns the folder name
// of the current working directory
func currentFolderName() string {
	dir, err := os.Getwd()
	panicIf(err)
	return filepath.Base(dir)
}
<commit_msg>Add buildName function<commit_after>package main

import (
	"fmt"
	"os"
	"path/filepath"
)

const (
	distRoot = "dist"
)

var (
	// targets for which to build
	// TODO: Get list from config file.
	gooses   = &[]string{"windows", "linux"}
	goarches = &[]string{"amd64", "386"}

	// name of the application
	name = currentFolderName()

	// version of the application
	version = gitVersion()
)

func main() {
	goGenerate()

	for _, goos := range *gooses {
		for _, goarch := range *goarches {
			buildName := buildName(name, version, goos, goarch)

			fmt.Println("Building " + buildName + "...")
			goBuild(goos, goarch, buildName)
		}
	}
}

func panicIf(err error) {
	if err != nil {
		panic(err.Error())
	}
}

// currentFolderName returns the folder name
// of the current working directory
func currentFolderName() string {
	dir, err := os.Getwd()
	panicIf(err)
	return filepath.Base(dir)
}

// buildName returns a build-name in the form of appname-version-os-arch
// ex: myapp-v1.0.0-linux-amd64
func buildName(name string, version string, os string, arch string) string {
	return name + "-" + version + "-" + os + "-" + arch
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
)

func main() {
	var resp EC2Response

	err := json.NewDecoder(os.Stdin).Decode(&resp)
	if err != nil {
		log.Fatal(err)
	}

	showName := func(tags []EC2InstanceTag) string {
		if len(tags) > 0 {
			for _, tag := range tags {
				if tag.Key == "Name" {
					return tag.Value
				}
			}
		}
		return "---"
	}

	var output string
	for _, res := range resp.Reservations {
		if output == "" {
			output = fmt.Sprintf("%30s %16s %16s %16s\n\n",
				"Server",
				"ID",
				"Private IP",
				"Public IP",
			)
		}
		for _, inst := range res.Instances {
			output += fmt.Sprintf("%30s %16s %16s %16s\n",
				showName(inst.Tags),
				inst.ID,
				inst.PrivateIP,
				inst.PublicIP,
			)
		}
	}

	if output != "" {
		fmt.Println(output)
	}
}

//EC2Response ...
type EC2Response struct {
	Reservations []EC2Result `json:"Reservations"`
}

//EC2Result ...
type EC2Result struct {
	Instances []EC2Instance `json:"Instances"`
}

//EC2Instance ...
type EC2Instance struct {
	ID        string           `json:"InstanceId"`
	PrivateIP string           `json:"PrivateIpAddress"`
	PublicIP  string           `json:"PublicIpAddress"`
	Tags      []EC2InstanceTag `json:"Tags"`
}

//EC2InstanceTag ...
type EC2InstanceTag struct {
	Key   string `json:"Key"`
	Value string `json:"Value"`
}
<commit_msg>adds instance state and moves instance name functionality out of main<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
)

func main() {
	var resp EC2Response

	err := json.NewDecoder(os.Stdin).Decode(&resp)
	if err != nil {
		log.Fatal(fmt.Errorf("error reading json string: %s", err))
	}

	var output string
	for _, res := range resp.Reservations {
		if output == "" {
			output = fmt.Sprintf("%30s%14s%11s%16s%18s\n\n",
				"Server",
				"ID",
				"State",
				"Private IP",
				"Public IP",
			)
		}
		for _, inst := range res.Instances {
			output += fmt.Sprintf("%30s%14s%11s%16s%18s\n",
				getInstanceNameFromTags(inst.Tags),
				inst.ID,
				inst.State.Name,
				inst.PrivateIP,
				inst.PublicIP,
			)
		}
	}

	if output != "" {
		fmt.Println(output)
	}
}

//getInstanceNameFromTags ...
func getInstanceNameFromTags(tags []EC2InstanceTag) string {
	if len(tags) > 0 {
		for _, tag := range tags {
			if tag.Key == "Name" {
				return tag.Value
			}
		}
	}
	return "---"
}

//EC2Response ...
type EC2Response struct {
	Reservations []EC2Result `json:"Reservations"`
}

//EC2Result ...
type EC2Result struct {
	Instances []EC2Instance `json:"Instances"`
}

//EC2Instance ...
type EC2Instance struct {
	ID        string           `json:"InstanceId"`
	PrivateIP string           `json:"PrivateIpAddress"`
	PublicIP  string           `json:"PublicIpAddress"`
	Tags      []EC2InstanceTag `json:"Tags"`
	State     EC2InstanceState `json:"State"`
}

//EC2InstanceState ...
type EC2InstanceState struct {
	Name string `json:"Name"`
}

//EC2InstanceTag ...
type EC2InstanceTag struct {
	Key   string `json:"Key"`
	Value string `json:"Value"`
}
<|endoftext|>


<commit_before>package main

import (
	"appengine"
	"appengine/user"
	"github.com/gorilla/sessions"
	"github.com/icco/natnatnat/handlers"
	"github.com/icco/natnatnat/models"
	"github.com/pilu/traffic"
	"html/template"
	"net/http"
	"time"
)

var store *sessions.CookieStore

func HstsMiddleware(w traffic.ResponseWriter, r *traffic.Request) {
	w.Header().Add("Strict-Transport-Security", "max-age=15768000")
}

func IsAdmin(c appengine.Context) bool {
	return c != nil && user.IsAdmin(c)
}

func fmtTime(t time.Time) string {
	const layout = "03:04 on Jan 2, 2006"
	return t.Format(layout)
}

func markdown(args ...interface{}) template.HTML {
	return models.Markdown(args...)
}

// init is one of those magic functions that runs once on project create.
func init() {
	if !appengine.IsDevAppServer() {
		traffic.SetVar("env", "production")
	}

	traffic.TemplateFunc("fmttime", fmtTime)
	traffic.TemplateFunc("mrkdwn", markdown)

	router := traffic.New()
	router.Get("/", handlers.RootHandler)
	router.Get("/about", handlers.AboutHandler)
	router.Get("/archives", handlers.UnimplementedHandler)
	router.Get("/stats", handlers.UnimplementedHandler)

	router.Get("/post/new/?", handlers.NewPostGetHandler)
	router.Post("/post/new/?", handlers.NewPostPostHandler)

	router.Get("/post/:id/?", handlers.PostHandler)

	router.Get("/edit/:id/?", handlers.EditPostGetHandler)
	router.Post("/edit/:id/?", handlers.EditPostPostHandler)

	router.Get("/settings", handlers.SettingsGetHandler)
	router.Post("/settings", handlers.SettingsPostHandler)

	router.Get("/mention", handlers.WebMentionGetHandler)
	router.Post("/mention", handlers.WebMentionPostHandler)

	router.Get("/feed.atom", handlers.FeedAtomHandler)
	router.Get("/feed.rss", handlers.FeedRssHandler)

	router.AddBeforeFilter(HstsMiddleware)
	router.Use(NewStaticMiddleware(traffic.PublicPath()))

	http.Handle("/", router)
}

// Entry point for go server.
func main() {}
<commit_msg>surface summary<commit_after>package main

import (
	"appengine"
	"appengine/user"
	"github.com/gorilla/sessions"
	"github.com/icco/natnatnat/handlers"
	"github.com/icco/natnatnat/models"
	"github.com/pilu/traffic"
	"html/template"
	"net/http"
	"time"
)

var store *sessions.CookieStore

func HstsMiddleware(w traffic.ResponseWriter, r *traffic.Request) {
	w.Header().Add("Strict-Transport-Security", "max-age=15768000")
}

func IsAdmin(c appengine.Context) bool {
	return c != nil && user.IsAdmin(c)
}

func fmtTime(t time.Time) string {
	const layout = "03:04 on Jan 2, 2006"
	return t.Format(layout)
}

func markdown(args ...interface{}) template.HTML {
	return models.Markdown(args...)
}

// init is one of those magic functions that runs once on project create.
func init() {
	if !appengine.IsDevAppServer() {
		traffic.SetVar("env", "production")
	}

	traffic.TemplateFunc("fmttime", fmtTime)
	traffic.TemplateFunc("mrkdwn", markdown)

	router := traffic.New()
	router.Get("/", handlers.RootHandler)
	router.Get("/about", handlers.AboutHandler)
	router.Get("/archives", handlers.UnimplementedHandler)
	router.Get("/stats", handlers.UnimplementedHandler)

	router.Get("/post/new/?", handlers.NewPostGetHandler)
	router.Post("/post/new/?", handlers.NewPostPostHandler)

	router.Get("/post/:id/?", handlers.PostHandler)

	router.Get("/edit/:id/?", handlers.EditPostGetHandler)
	router.Post("/edit/:id/?", handlers.EditPostPostHandler)

	router.Get("/settings", handlers.SettingsGetHandler)
	router.Post("/settings", handlers.SettingsPostHandler)

	router.Get("/mention", handlers.WebMentionGetHandler)
	router.Post("/mention", handlers.WebMentionPostHandler)

	router.Get("/feed.atom", handlers.FeedAtomHandler)
	router.Get("/feed.rss", handlers.FeedRssHandler)

	router.Get("/summary.atom", handlers.SummaryAtomHandler)
	router.Get("/summary.rss", handlers.SummaryRssHandler)

	router.AddBeforeFilter(HstsMiddleware)
	router.Use(NewStaticMiddleware(traffic.PublicPath()))

	http.Handle("/", router)
}

// Entry point for go server.
func main() {}
<|endoftext|>


<commit_before>package main

import (
    "log"
    "net/http"
)

func pingServer(w http.ResponseWriter, req *http.Request) {
    w.Write([]byte("Hello Drone!"))
}

func main() {
    http.HandleFunc("/", pingServer)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}
<commit_msg>trigger<commit_after>package main

import (
    "log"
    "net/http"
)

func pingServer(w http.ResponseWriter, req *http.Request) {
    w.Write([]byte("Built by Drone!"))
}

func main() {
    http.HandleFunc("/", pingServer)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"time"

	"github.com/gorilla/mux"
	"github.com/rubyist/circuitbreaker"
)

var breaker = circuit.NewConsecutiveBreaker(5)

// DriverLocation models response from LocationService
type DriverLocation struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	UpdatedAt string  `json:"updated_at"`
}

// APIResponse models the response to know if a driver is active
type APIResponse struct {
	ID     int  `json:"id"`
	Zombie bool `json:"zombie"`
}

func main() {
	r := mux.NewRouter().StrictSlash(true)
	r.HandleFunc("/drivers/{id:[0-9]+}", ZombieDriverHandler).Methods("GET")
	http.Handle("/", r)
	log.Printf("Server started and listening on port %d.", 1338)
	log.Fatal(http.ListenAndServe(":1338", nil))
}

// ZombieDriverHandler handles a user's request to know if a driver is active
func ZombieDriverHandler(w http.ResponseWriter, r *http.Request) {
	log.Printf("\t%s",
		r.RequestURI)
	// Read route parameter
	vars := mux.Vars(r)
	param := vars["id"]
	driverID, err := strconv.Atoi(param)
	if err != nil {
		log.Printf("Received bad request with driver id %s.", param)
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	locationURL := fmt.Sprintf("http://localhost:1339/drivers/%d", driverID)
	locations, err := getDriverLocations(breaker, locationURL)
	if err != nil {
		log.Printf(err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	isZombie := isDriverZombie(locations)

	result := APIResponse{ID: driverID, Zombie: isZombie}
	w.Header().Set("Content-Type", "application/json")
	response, err := json.Marshal(result)
	if err != nil {
		log.Printf(err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Write(response)
	return
}

func getDriverLocations(breaker *circuit.Breaker, serviceURL string) ([]*DriverLocation, error) {
	// return []*DriverLocation{
	// 	&DriverLocation{
	// 		Latitude:  42,
	// 		Longitude: 2.3,
	// 		UpdatedAt: "2016-06-10T19:43:22.232Z",
	// 	},
	// 	&DriverLocation{
	// 		Latitude:  42,
	// 		Longitude: 2.3,
	// 		UpdatedAt: "2016-06-10T19:43:22.232Z",
	// 	},
	// }, nil
	var response *http.Response
	var err error
	err = breaker.Call(func() error {
		var httpErr error
		response, httpErr = http.Get(serviceURL)
		return httpErr
	}, time.Second*1)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	decoder := json.NewDecoder(response.Body)
	var locations []*DriverLocation
	if err := decoder.Decode(&locations); err != nil {
		return nil, err
	}
	return locations, nil
}

func isDriverZombie(locations []*DriverLocation) bool {
	return false
}
<commit_msg>Updated location service URL<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"time"

	"github.com/gorilla/mux"
	"github.com/rubyist/circuitbreaker"
)

var breaker = circuit.NewConsecutiveBreaker(5)

// DriverLocation models response from LocationService
type DriverLocation struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	UpdatedAt string  `json:"updated_at"`
}

// APIResponse models the response to know if a driver is active
type APIResponse struct {
	ID     int  `json:"id"`
	Zombie bool `json:"zombie"`
}

func main() {
	r := mux.NewRouter().StrictSlash(true)
	r.HandleFunc("/drivers/{id:[0-9]+}", ZombieDriverHandler).Methods("GET")
	http.Handle("/", r)
	log.Printf("Server started and listening on port %d.", 1338)
	log.Fatal(http.ListenAndServe(":1338", nil))
}

// ZombieDriverHandler handles a user's request to know if a driver is active
func ZombieDriverHandler(w http.ResponseWriter, r *http.Request) {
	log.Printf("\t%s",
		r.RequestURI)
	// Read route parameter
	vars := mux.Vars(r)
	param := vars["id"]
	driverID, err := strconv.Atoi(param)
	if err != nil {
		log.Printf("Received bad request with driver id %s.", param)
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	locationURL := fmt.Sprintf("http://localhost:8001/drivers/%d", driverID)
	locations, err := getDriverLocations(breaker, locationURL)
	if err != nil {
		log.Printf(err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	isZombie := isDriverZombie(locations)

	result := APIResponse{ID: driverID, Zombie: isZombie}
	w.Header().Set("Content-Type", "application/json")
	response, err := json.Marshal(result)
	if err != nil {
		log.Printf(err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Write(response)
	return
}

func getDriverLocations(breaker *circuit.Breaker, serviceURL string) ([]*DriverLocation, error) {
	// return []*DriverLocation{
	// 	&DriverLocation{
	// 		Latitude:  42,
	// 		Longitude: 2.3,
	// 		UpdatedAt: "2016-06-10T19:43:22.232Z",
	// 	},
	// 	&DriverLocation{
	// 		Latitude:  42,
	// 		Longitude: 2.3,
	// 		UpdatedAt: "2016-06-10T19:43:22.232Z",
	// 	},
	// }, nil
	var response *http.Response
	var err error
	err = breaker.Call(func() error {
		var httpErr error
		response, httpErr = http.Get(serviceURL)
		return httpErr
	}, time.Second*1)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	decoder := json.NewDecoder(response.Body)
	var locations []*DriverLocation
	if err := decoder.Decode(&locations); err != nil {
		return nil, err
	}
	return locations, nil
}

func isDriverZombie(locations []*DriverLocation) bool {
	return false
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"strings"
	"time"
	"net/http"
	"encoding/json"
	"github.com/rancher/go-rancher/client"
	"os"
)

type Rancher struct {
	Url        string `json:"url"`
	AccessKey  string `json:"access_key"`
	SecretKey  string `json:"secret_key"`
	Service    string `json:"service"`
	Image      string `json:"docker_image"`
	StartFirst bool   `json:"start_first"`
	Confirm    bool   `json:"confirm"`
	Timeout    int    `json:"timeout"`
}

func main() {
	fmt.Printf("Started upgrade server\n")
	http.HandleFunc("/upgrade/", requestSuccess)
	http.ListenAndServe(":8080", nil)
}

func requestSuccess(w http.ResponseWriter, r *http.Request){
	vargs := Rancher{
		StartFirst: true,
		Timeout:    30,
	}

	err := json.NewDecoder(r.Body).Decode(&vargs)
	if err != nil {
		fmt.Printf(err.Error())
		Error(w, err.Error(), 400)
		return
	} else {
		if len(vargs.Url) == 0 || len(vargs.AccessKey) == 0 || len(vargs.SecretKey) == 0 {
			Error(w, "Rancher credentials not set", 400)
			return
		}
		go upgradeRancher(vargs)
		w.WriteHeader(200)
		return
	}
}

func upgradeRancher(vargs Rancher) {
	var wantedImage, wantedVer string
	if !strings.HasPrefix(vargs.Image, "docker:") {
		vargs.Image = fmt.Sprintf("docker:%s", vargs.Image)
		parts := strings.Split(vargs.Image, ":")
		wantedImage = parts[1]
		wantedVer = parts[2]
	}

	var wantedService, wantedStack string
	if strings.Contains(vargs.Service, "/") {
		parts := strings.SplitN(vargs.Service, "/", 2)
		wantedStack = parts[0]
		wantedService = parts[1]
	} else if vargs.Service != "" {
		wantedService = vargs.Service
	}

	rancher, err := client.NewRancherClient(&client.ClientOpts{
		Url:       vargs.Url,
		AccessKey: vargs.AccessKey,
		SecretKey: vargs.SecretKey,
	})

	if err != nil {
		fmt.Printf("Failed to create rancher client: %s\n", err)
		return
	}

	var stackId string
	if wantedStack != "" {
		environments, err := rancher.Environment.List(&client.ListOpts{})
		if err != nil {
			fmt.Printf("Failed to list rancher environments: %s\n", err)
			return
		}

		for _, env := range environments.Data {
			if env.Name == wantedStack {
				stackId = env.Id
			}
		}

		if stackId == "" {
			fmt.Printf("Unable to find stack %s\n", wantedStack)
			return
		}
	}

	services, err := rancher.Service.List(&client.ListOpts{})
	if err != nil {
		fmt.Printf("Failed to list rancher services: %s\n", err)
		return
	}

	var upgradeLabel = os.Getenv("UPGRADE_LABEL")

	var foundImage, foundVer string
	for services != nil {
		for _, svc := range services.Data {
			if svc.LaunchConfig != nil {
				if _, ok := svc.LaunchConfig.Labels[upgradeLabel]; ok {
					parts := strings.Split(svc.LaunchConfig.ImageUuid, ":")
					foundImage = parts[1]
					foundVer = parts[2]
					if foundImage == wantedImage && ((foundVer < wantedVer) || (wantedVer == "latest")) {
						fmt.Printf("Trying to upgrade...\n")
						err := doUpgrade(vargs, svc, rancher)
						if err != nil {
							fmt.Printf(err.Error())
						}
						if (vargs.Confirm) {
							fmt.Printf("Trying to confirm...\n")
							err := confirmUpgrade(vargs, svc, rancher)
							if err != nil {
								fmt.Printf(err.Error())
							}
						}
						continue
					}
					if svc.Name == wantedService && ((wantedStack != "" && svc.EnvironmentId == stackId) || wantedStack == "") {
						err := doUpgrade(vargs, svc, rancher)
						if err != nil {
							fmt.Printf(err.Error())
						}
						if vargs.Confirm {
							err := confirmUpgrade(vargs, svc, rancher)
							if err != nil {
								fmt.Printf(err.Error())
							}
						}
					}
				}
			}
		}
		services, err = services.Next()
	}
}

func doUpgrade(vargs Rancher, service client.Service, rancher *client.RancherClient) (error) {
	service.LaunchConfig.ImageUuid = vargs.Image
	upgrade := &client.ServiceUpgrade{}
	upgrade.InServiceStrategy = &client.InServiceUpgradeStrategy{
		LaunchConfig:           service.LaunchConfig,
		SecondaryLaunchConfigs: service.SecondaryLaunchConfigs,
		StartFirst:             vargs.StartFirst,
	}
	upgrade.ToServiceStrategy = &client.ToServiceUpgradeStrategy{}

	_, err := rancher.Service.ActionUpgrade(&service, upgrade)
	if err != nil {
		fmt.Printf("Unable to upgrade service %s: %s\n", vargs.Service, err)
	} else {
		fmt.Printf("Upgraded %s to %s\n", service.Name, vargs.Image)
	}
	return err
}

func confirmUpgrade(vargs Rancher, service client.Service, rancher *client.RancherClient) (error) {
	srv, err := retry(func() (interface{}, error) {
		s, e := rancher.Service.ById(service.Id)
		if e != nil {
			return nil, e
		}
		if s.State != "upgraded" {
			return nil, fmt.Errorf("Service not upgraded: %s", s.State)
		}
		return s, nil
	}, time.Duration(vargs.Timeout)*time.Second, 3*time.Second)

	if err != nil {
		fmt.Printf("Error waiting for service upgrade to complete: %s", err)
		return err
	}

	_, err = rancher.Service.ActionFinishupgrade(srv.(*client.Service))
	if err != nil {
		fmt.Printf("Unable to finish upgrade %s: %s\n", vargs.Service, err)
		return err
	}
	fmt.Printf("Finished upgrade %s\n", vargs.Service)
	return err
}

type retryFunc func() (interface{}, error)

func retry(f retryFunc, timeout time.Duration, interval time.Duration) (interface{}, error) {
	finish := time.After(timeout)
	for {
		result, err := f()
		if err == nil {
			return result, nil
		}
		select {
		case <-finish:
			return nil, err
		case <-time.After(interval):
		}
	}
}

func Error(w http.ResponseWriter, error string, code int) {
	w.Header().Set("Content Type,", "text/plain; charset=UTF-8")
	w.WriteHeader(code)
	fmt.Fprint(w, error)
}<commit_msg>remove default start first<commit_after>package main

import (
	"fmt"
	"strings"
	"time"
	"net/http"
	"encoding/json"
	"github.com/rancher/go-rancher/client"
	"os"
)

type Rancher struct {
	Url        string `json:"url"`
	AccessKey  string `json:"access_key"`
	SecretKey  string `json:"secret_key"`
	Service    string `json:"service"`
	Image      string `json:"docker_image"`
	StartFirst bool   `json:"start_first"`
	Confirm    bool   `json:"confirm"`
	Timeout    int    `json:"timeout"`
}

func main() {
	fmt.Printf("Started upgrade server\n")
	http.HandleFunc("/upgrade/", requestSuccess)
	http.ListenAndServe(":8080", nil)
}

func requestSuccess(w http.ResponseWriter, r *http.Request){
	vargs := Rancher{
		StartFirst: false,
		Timeout:    30,
	}

	err := json.NewDecoder(r.Body).Decode(&vargs)
	if err != nil {
		fmt.Printf(err.Error())
		Error(w, err.Error(), 400)
		return
	} else {
		if len(vargs.Url) == 0 || len(vargs.AccessKey) == 0 || len(vargs.SecretKey) == 0 {
			Error(w, "Rancher credentials not set", 400)
			return
		}
		go upgradeRancher(vargs)
		w.WriteHeader(200)
		return
	}
}

func upgradeRancher(vargs Rancher) {
	var wantedImage, wantedVer string
	if !strings.HasPrefix(vargs.Image, "docker:") {
		vargs.Image = fmt.Sprintf("docker:%s", vargs.Image)
		parts := strings.Split(vargs.Image, ":")
		wantedImage = parts[1]
		wantedVer = parts[2]
	}

	var wantedService, wantedStack string
	if strings.Contains(vargs.Service, "/") {
		parts := strings.SplitN(vargs.Service, "/", 2)
		wantedStack = parts[0]
		wantedService = parts[1]
	} else if vargs.Service != "" {
		wantedService = vargs.Service
	}

	rancher, err := client.NewRancherClient(&client.ClientOpts{
		Url:       vargs.Url,
		AccessKey: vargs.AccessKey,
		SecretKey: vargs.SecretKey,
	})

	if err != nil {
		fmt.Printf("Failed to create rancher client: %s\n", err)
		return
	}

	var stackId string
	if wantedStack != "" {
		environments, err := rancher.Environment.List(&client.ListOpts{})
		if err != nil {
			fmt.Printf("Failed to list rancher environments: %s\n", err)
			return
		}

		for _, env := range environments.Data {
			if env.Name == wantedStack {
				stackId = env.Id
			}
		}

		if stackId == "" {
			fmt.Printf("Unable to find stack %s\n", wantedStack)
			return
		}
	}

	services, err := rancher.Service.List(&client.ListOpts{})
	if err != nil {
		fmt.Printf("Failed to list rancher services: %s\n", err)
		return
	}

	var upgradeLabel = os.Getenv("UPGRADE_LABEL")

	var foundImage, foundVer string
	for services != nil {
		for _, svc := range services.Data {
			if svc.LaunchConfig != nil {
				if _, ok := svc.LaunchConfig.Labels[upgradeLabel]; ok {
					parts := strings.Split(svc.LaunchConfig.ImageUuid, ":")
					foundImage = parts[1]
					foundVer = parts[2]
					if foundImage == wantedImage && ((foundVer < wantedVer) || (wantedVer == "latest")) {
						fmt.Printf("Trying to upgrade...\n")
						err := doUpgrade(vargs, svc, rancher)
						if err != nil {
							fmt.Printf(err.Error())
						}
						if (vargs.Confirm) {
							fmt.Printf("Trying to confirm...\n")
							err := confirmUpgrade(vargs, svc, rancher)
							if err != nil {
								fmt.Printf(err.Error())
							}
						}
						continue
					}
					if svc.Name == wantedService && ((wantedStack != "" && svc.EnvironmentId == stackId) || wantedStack == "") {
						err := doUpgrade(vargs, svc, rancher)
						if err != nil {
							fmt.Printf(err.Error())
						}
						if vargs.Confirm {
							err := confirmUpgrade(vargs, svc, rancher)
							if err != nil {
								fmt.Printf(err.Error())
							}
						}
					}
				}
			}
		}
		services, err = services.Next()
	}
}

func doUpgrade(vargs Rancher, service client.Service, rancher *client.RancherClient) (error) {
	service.LaunchConfig.ImageUuid = vargs.Image
	upgrade := &client.ServiceUpgrade{}
	upgrade.InServiceStrategy = &client.InServiceUpgradeStrategy{
		LaunchConfig:           service.LaunchConfig,
		SecondaryLaunchConfigs: service.SecondaryLaunchConfigs,
		StartFirst:             vargs.StartFirst,
	}
	upgrade.ToServiceStrategy = &client.ToServiceUpgradeStrategy{}

	_, err := rancher.Service.ActionUpgrade(&service, upgrade)
	if err != nil {
		fmt.Printf("Unable to upgrade service %s: %s\n", vargs.Service, err)
	} else {
		fmt.Printf("Upgraded %s to %s\n", service.Name, vargs.Image)
	}
	return err
}

func confirmUpgrade(vargs Rancher, service client.Service, rancher *client.RancherClient) (error) {
	srv, err := retry(func() (interface{}, error) {
		s, e := rancher.Service.ById(service.Id)
		if e != nil {
			return nil, e
		}
		if s.State != "upgraded" {
			return nil, fmt.Errorf("Service not upgraded: %s", s.State)
		}
		return s, nil
	}, time.Duration(vargs.Timeout)*time.Second, 3*time.Second)

	if err != nil {
		fmt.Printf("Error waiting for service upgrade to complete: %s", err)
		return err
	}

	_, err = rancher.Service.ActionFinishupgrade(srv.(*client.Service))
	if err != nil {
		fmt.Printf("Unable to finish upgrade %s: %s\n", vargs.Service, err)
		return err
	}
	fmt.Printf("Finished upgrade %s\n", vargs.Service)
	return err
}

type retryFunc func() (interface{}, error)

func retry(f retryFunc, timeout time.Duration, interval time.Duration) (interface{}, error) {
	finish := time.After(timeout)
	for {
		result, err := f()
		if err == nil {
			return result, nil
		}
		select {
		case <-finish:
			return nil, err
		case <-time.After(interval):
		}
	}
}

func Error(w http.ResponseWriter, error string, code int) {
	w.Header().Set("Content Type,", "text/plain; charset=UTF-8")
	w.WriteHeader(code)
	fmt.Fprint(w, error)
}<|endoftext|>


<commit_before>package main // import "github.com/tutumcloud/weave-daemon"

import (
	"log"
	"os"
	"os/exec"
	"strings"
	"time"

	"github.com/fsouza/go-dockerclient"
	"github.com/tutumcloud/go-tutum/tutum"
	"github.com/tutumcloud/weave-daemon/nodes"
)

func AttachContainer(c *docker.Client, container_id string) error {
	inspect, err := c.InspectContainer(container_id)

	if err != nil {
		log.Println("Inspecting Containers failed")
		return err
	}

	cidr := ""
	env_vars := inspect.Config.Env

	for i := range env_vars {
		if strings.HasPrefix(env_vars[i], "TUTUM_IP_ADDRESS=") {
			cidr = env_vars[i][len("TUTUM_IP_ADDRESS="):]
			break
		}
	}

	if cidr != "" {
		tries := 0
		for tries < 3 {

			log.Printf("%s: adding to weave with IP %s", container_id, cidr)
			cmd := exec.Command("/weave", "--local", "attach", cidr, container_id)

			_, err := cmd.StdoutPipe()
			if err != nil {
				return err
			}

			if err := cmd.Start(); err != nil {
				log.Println("Start weave cmd failed")
				return err
			}

			if err := cmd.Wait(); err != nil {
				tries++
				log.Println("Wait weave cmd failed")
				if tries > 3 {
					return err
				}
			} else {
				break
			}
		}
	} else {
		log.Printf("%s: cannot find the IP address to add to weave", container_id)
	}
	return nil
}

func ContainerAttachThread(c *docker.Client) error {

	listener := make(chan *docker.APIEvents)

	containers, err := c.ListContainers(docker.ListContainersOptions{All: false, Size: true, Limit: 0, Since: "", Before: ""})
	if err != nil {
		log.Println("Listing Containers failed")
		return err
	}

	for _, container := range containers {
		err := AttachContainer(c, container.ID)
		if err != nil {
			log.Println("Attaching Containers failed")
			return err
		}

	}
	err = c.AddEventListener(listener)
	if err != nil {
		log.Println("Listening Containers Events failed")
		return err
	}

	defer func() error {

		err = c.RemoveEventListener(listener)
		if err != nil {
			return err
		}
		return nil
	}()

	timeout := time.After(1 * time.Second)

	for {
		select {
		case msg := <-listener:
			if msg.Status == "start" && !strings.HasPrefix(msg.From, "weaveworks/weave") {
				err := AttachContainer(c, msg.ID)
				if err != nil {
					log.Println("Attaching Containers failed")
					log.Println(err)
					break
				}
				time.Sleep(2 * time.Second)
			}
		case <-timeout:
			break
		}
	}
}

func discovering() {
	c := make(chan tutum.Event)
	e := make(chan error)
	nodes.DiscoverPeers()
	go tutum.TutumEvents(c, e)
Loop:
	for {
		select {
		case event := <-c:
			if event.Type == "node" && (event.State == "Deployed" || event.State == "Terminated") {
				err := nodes.DiscoverPeers()
				if err != nil {
					log.Println(err)
				}
				time.Sleep(2 * time.Second)
			}
		case err := <-e:
			log.Println(err)
			time.Sleep(5 * time.Second)
			go discovering()
			break Loop
		}
	}
}

func connectToDocker() (*docker.Client, error) {
	endpoint := "unix:///var/run/docker.sock"

	client, err := docker.NewClient(endpoint)

	if err != nil {

		log.Println(err)
	}
	return client, nil
}

func main() {

	log.Println("Start running daemon")

	//Init Docker client
	client, err := connectToDocker()
	if err != nil {
		log.Println(err)
	}

	node, err := tutum.GetNode(nodes.Tutum_Node_Api_Uri)
	if err != nil {
		log.Println(err)
	}
	nodes.Tutum_Node_Public_Ip = node.Public_ip
	log.Printf("This node IP is %s", nodes.Tutum_Node_Public_Ip)
	if os.Getenv("TUTUM_AUTH") != "" {
		log.Println("Detected Tutum API access - starting peer discovery thread")
		go discovering()
	}
	for {
		err := ContainerAttachThread(client)
		if err != nil {
			log.Println("ATTACH ERROR")
			log.Println(err)
			time.Sleep(15 * time.Second)
		}
	}
}
<commit_msg>fix weave error handeling<commit_after>package main // import "github.com/tutumcloud/weave-daemon"

import (
	"log"
	"os"
	"os/exec"
	"strings"
	"time"

	"github.com/fsouza/go-dockerclient"
	"github.com/tutumcloud/go-tutum/tutum"
	"github.com/tutumcloud/weave-daemon/nodes"
)

func AttachContainer(c *docker.Client, container_id string) error {
	inspect, err := c.InspectContainer(container_id)

	if err != nil {
		log.Println("Inspecting Containers failed")
		return err
	}

	cidr := ""
	env_vars := inspect.Config.Env

	for i := range env_vars {
		if strings.HasPrefix(env_vars[i], "TUTUM_IP_ADDRESS=") {
			cidr = env_vars[i][len("TUTUM_IP_ADDRESS="):]
			break
		}
	}

	if cidr != "" {
		tries := 0
		for {

			log.Printf("%s: adding to weave with IP %s", container_id, cidr)
			cmd := exec.Command("/weave", "--local", "attach", cidr, container_id)

			_, err := cmd.StdoutPipe()
			if err != nil {
				return err
			}

			if err := cmd.Start(); err != nil {
				tries++
				log.Println("Start weave cmd failed")
				if tries > 3 {
					return err
				}
			}

			if err := cmd.Wait(); err != nil {
				tries++
				log.Println("Wait weave cmd failed")
				if tries > 3 {
					return err
				}
			} else {
				break
			}
		}
	} else {
		log.Printf("%s: cannot find the IP address to add to weave", container_id)
	}
	return nil
}

func ContainerAttachThread(c *docker.Client) error {

	listener := make(chan *docker.APIEvents)

	containers, err := c.ListContainers(docker.ListContainersOptions{All: false, Size: true, Limit: 0, Since: "", Before: ""})
	if err != nil {
		log.Println("Listing Containers failed")
		return err
	}

	for _, container := range containers {
		err := AttachContainer(c, container.ID)
		if err != nil {
			log.Println("Attaching Containers failed")
			return err
		}

	}
	err = c.AddEventListener(listener)
	if err != nil {
		log.Println("Listening Containers Events failed")
		return err
	}

	defer func() error {

		err = c.RemoveEventListener(listener)
		if err != nil {
			return err
		}
		return nil
	}()

	timeout := time.After(1 * time.Second)

	for {
		select {
		case msg := <-listener:
			if msg.Status == "start" && !strings.HasPrefix(msg.From, "weaveworks/weave") {
				err := AttachContainer(c, msg.ID)
				if err != nil {
					log.Println("Attaching Containers failed")
					log.Println(err)
					break
				}
				time.Sleep(2 * time.Second)
			}
		case <-timeout:
			break
		}
	}
}

func discovering() {
	c := make(chan tutum.Event)
	e := make(chan error)
	nodes.DiscoverPeers()
	go tutum.TutumEvents(c, e)
Loop:
	for {
		select {
		case event := <-c:
			if event.Type == "node" && (event.State == "Deployed" || event.State == "Terminated") {
				err := nodes.DiscoverPeers()
				if err != nil {
					log.Println(err)
				}
				time.Sleep(2 * time.Second)
			}
		case err := <-e:
			log.Println(err)
			time.Sleep(5 * time.Second)
			go discovering()
			break Loop
		}
	}
}

func connectToDocker() (*docker.Client, error) {
	endpoint := "unix:///var/run/docker.sock"

	client, err := docker.NewClient(endpoint)

	if err != nil {

		log.Println(err)
	}
	return client, nil
}

func main() {

	log.Println("Start running daemon")

	//Init Docker client
	client, err := connectToDocker()
	if err != nil {
		log.Println(err)
	}

	node, err := tutum.GetNode(nodes.Tutum_Node_Api_Uri)
	if err != nil {
		log.Println(err)
	}
	nodes.Tutum_Node_Public_Ip = node.Public_ip
	log.Printf("This node IP is %s", nodes.Tutum_Node_Public_Ip)
	if os.Getenv("TUTUM_AUTH") != "" {
		log.Println("Detected Tutum API access - starting peer discovery thread")
		go discovering()
	}
	for {
		err := ContainerAttachThread(client)
		if err != nil {
			log.Println("ATTACH ERROR")
			log.Println(err)
			time.Sleep(15 * time.Second)
		}
	}
}
<|endoftext|>


<commit_before>/*

Simple File Transfer

Copyright (c) 2014 Dmitry Lagoza
Use of this source code is governed by a MIT
license that can be found in the LICENSE file.

WWW: http://lagoza.name/
Email: dmitry@lagoza.name

*/

package main

import (
	"fmt"
	flag "github.com/dotcloud/docker/pkg/mflag"
	"io"
	"net"
	"os"
	"strconv"
)

var (
	port               int
	s, d, h, verbose   bool
	filename, hostname string
)

func PrintDefaults() {
	fmt.Fprintf(os.Stderr, "usage: %s [[-s|--source]|[-d|--destination]] [-p num|--port=num] [-h|--help] [HOSTNAME] FILENAME\n", os.Args[0])
	flag.PrintDefaults()
	fmt.Fprintln(os.Stderr, "  HOSTNAME\tserver hostname or IP to connect to")
	fmt.Fprintln(os.Stderr, "  FILENAME\tname of file to send or recieve")
}

func init() {
	flag.Usage = PrintDefaults
	flag.BoolVar(&s, []string{"s", "-source"}, false, "start as source server (send FILENAME to client)")
	flag.BoolVar(&d, []string{"d", "-destination"}, false, "start as destination server (recieve FILENAME to client)")
	flag.IntVar(&port, []string{"p", "-port"}, -1, "use port")
	flag.BoolVar(&h, []string{"h", "-help"}, false, "display this help")
	flag.BoolVar(&verbose, []string{"v", "-verbose"}, false, "be verbose")
	flag.Parse()
	if h {
		PrintDefaults()
		os.Exit(0)
	}
	if flag.NArg() < 1 {
		fmt.Fprintln(os.Stderr, "Please specify the file!")
		PrintDefaults()
		os.Exit(1)
	}
	if d && s {
		fmt.Fprintln(os.Stderr, "You can use source OR destination flag, not both!")
		PrintDefaults()
		os.Exit(1)
	}
	if (d || s) && flag.NArg() > 1 {
		fmt.Fprintln(os.Stderr, "For server mode don't specify HOSTNAME! You can use -d or -s or HOSTNAME.")
		PrintDefaults()
		os.Exit(1)
	}
	if (!d && !s) && flag.NArg() < 2 {
		fmt.Fprintln(os.Stderr, "For client mode specify HOSTNAME!")
		PrintDefaults()
		os.Exit(1)
	}

}

func Server() {
	filename = flag.Arg(0)
	if port == -1 {
		port = 18000
	}
	if d {
		if verbose {
			fmt.Fprintln(os.Stderr, "Mode: Destination\nPort: "+strconv.Itoa(port)+"\nFile: "+filename)
		}

		ln, err := net.Listen("tcp", ":"+strconv.Itoa(port))
		if err != nil {
			os.Exit(1)
		}
		defer ln.Close()
		if verbose {
			fmt.Fprint(os.Stderr, "Waiting for connection... ")
		}
		conn, err := ln.Accept()
		if err != nil {
			os.Exit(1)
		}
		defer conn.Close()
		if verbose {
			fmt.Fprintln(os.Stderr, "connected from "+conn.RemoteAddr().String())
		}
		var f *os.File
		if filename == "-" {
			f = os.Stdout
		} else {
			f, err = os.Create(filename)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Error while file creation:", err)
				os.Exit(1)
			}
		}
		defer f.Close()
		fmt.Fprint(conn, "D")
		written, err := io.Copy(f, conn)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error while Copy:", err)
			os.Exit(1)
		}
		if verbose {
			fmt.Fprintln(os.Stderr, "Recieved "+strconv.Itoa(int(written))+" bytes")
		}
	}
	//Source
	if s {
		if verbose {
			fmt.Fprintln(os.Stderr, "Mode: Source\nPort: "+strconv.Itoa(port)+"\nFile: "+filename)
		}

		ln, err := net.Listen("tcp", ":"+strconv.Itoa(port))
		if err != nil {
			os.Exit(1)
		}
		defer ln.Close()
		if verbose {
			fmt.Fprint(os.Stderr, "Waiting for connection... ")
		}
		conn, err := ln.Accept()
		if err != nil {
			os.Exit(1)
		}
		defer conn.Close()
		if verbose {
			fmt.Fprintln(os.Stderr, "connected from "+conn.RemoteAddr().String())
		}
		var f *os.File
		if filename == "-" {
			f = os.Stdin
		} else {
			f, err = os.Open(filename)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Error while file opening:", err)
				os.Exit(1)
			}
		}
		defer f.Close()
		fmt.Fprint(conn, "S")
		written, err := io.Copy(conn, f)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error while Copy:", err)
			os.Exit(1)
		}
		if verbose {
			fmt.Fprintln(os.Stderr, "Sent "+strconv.Itoa(int(written))+" bytes")
		}
	}
}

func Client() {
	hostname = flag.Arg(0)
	filename = flag.Arg(1)
	if port == -1 {
		port = 18000
	}
	if verbose {
		fmt.Fprintln(os.Stderr, "Client mode")
	}
	fmt.Fprintln(os.Stderr, "Port: "+strconv.Itoa(port)+"\nFile: "+filename)
	fmt.Fprint(os.Stderr, "Connecting... ")
	conn, err := net.Dial("tcp", hostname+":"+strconv.Itoa(port))
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error while file connecting:", err)
		os.Exit(1)
	}
	defer conn.Close()
	fmt.Fprintln(os.Stderr, "ok")
	mode := make([]byte, 1)
	conn.Read(mode)
	switch mode[0] {
	default:
		fmt.Fprintln(os.Stderr, "Unknown server mode")
		os.Exit(1)
	case 'D':
		var f *os.File
		if filename == "-" {
			f = os.Stdin
		} else {
			f, err = os.Open(filename)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Error while file open:", err)
				os.Exit(1)
			}
		}
		defer f.Close()
		fmt.Fprintln(os.Stderr, "Mode: Destination")
		io.Copy(conn, f)
	case 'S':
		var f *os.File
		if filename == "-" {
			f = os.Stdout
		} else {
			f, err = os.Create(filename)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Error while file creation:", err)
				os.Exit(1)
			}
		}
		defer f.Close()
		fmt.Fprintln(os.Stderr, "Mode: Source")
		io.Copy(f, conn)
	}
}

func main() {
	if d || s {
		Server()
	} else {
		Client()
	}
}
<commit_msg>Change mflag package URL<commit_after>/*

Simple File Transfer

Copyright (c) 2014 Dmitry Lagoza
Use of this source code is governed by a MIT
license that can be found in the LICENSE file.

WWW: http://lagoza.name/
Email: dmitry@lagoza.name

*/

package main

import (
	"fmt"
	flag "github.com/docker/docker/pkg/mflag"
	"io"
	"net"
	"os"
	"strconv"
)

var (
	port               int
	s, d, h, verbose   bool
	filename, hostname string
)

func PrintDefaults() {
	fmt.Fprintf(os.Stderr, "usage: %s [[-s|--source]|[-d|--destination]] [-p num|--port=num] [-h|--help] [HOSTNAME] FILENAME\n", os.Args[0])
	flag.PrintDefaults()
	fmt.Fprintln(os.Stderr, "  HOSTNAME\tserver hostname or IP to connect to")
	fmt.Fprintln(os.Stderr, "  FILENAME\tname of file to send or recieve")
}

func init() {
	flag.Usage = PrintDefaults
	flag.BoolVar(&s, []string{"s", "-source"}, false, "start as source server (send FILENAME to client)")
	flag.BoolVar(&d, []string{"d", "-destination"}, false, "start as destination server (recieve FILENAME to client)")
	flag.IntVar(&port, []string{"p", "-port"}, -1, "use port")
	flag.BoolVar(&h, []string{"h", "-help"}, false, "display this help")
	flag.BoolVar(&verbose, []string{"v", "-verbose"}, false, "be verbose")
	flag.Parse()
	if h {
		PrintDefaults()
		os.Exit(0)
	}
	if flag.NArg() < 1 {
		fmt.Fprintln(os.Stderr, "Please specify the file!")
		PrintDefaults()
		os.Exit(1)
	}
	if d && s {
		fmt.Fprintln(os.Stderr, "You can use source OR destination flag, not both!")
		PrintDefaults()
		os.Exit(1)
	}
	if (d || s) && flag.NArg() > 1 {
		fmt.Fprintln(os.Stderr, "For server mode don't specify HOSTNAME! You can use -d or -s or HOSTNAME.")
		PrintDefaults()
		os.Exit(1)
	}
	if (!d && !s) && flag.NArg() < 2 {
		fmt.Fprintln(os.Stderr, "For client mode specify HOSTNAME!")
		PrintDefaults()
		os.Exit(1)
	}

}

func Server() {
	filename = flag.Arg(0)
	if port == -1 {
		port = 18000
	}
	if d {
		if verbose {
			fmt.Fprintln(os.Stderr, "Mode: Destination\nPort: "+strconv.Itoa(port)+"\nFile: "+filename)
		}

		ln, err := net.Listen("tcp", ":"+strconv.Itoa(port))
		if err != nil {
			os.Exit(1)
		}
		defer ln.Close()
		if verbose {
			fmt.Fprint(os.Stderr, "Waiting for connection... ")
		}
		conn, err := ln.Accept()
		if err != nil {
			os.Exit(1)
		}
		defer conn.Close()
		if verbose {
			fmt.Fprintln(os.Stderr, "connected from "+conn.RemoteAddr().String())
		}
		var f *os.File
		if filename == "-" {
			f = os.Stdout
		} else {
			f, err = os.Create(filename)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Error while file creation:", err)
				os.Exit(1)
			}
		}
		defer f.Close()
		fmt.Fprint(conn, "D")
		written, err := io.Copy(f, conn)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error while Copy:", err)
			os.Exit(1)
		}
		if verbose {
			fmt.Fprintln(os.Stderr, "Recieved "+strconv.Itoa(int(written))+" bytes")
		}
	}
	//Source
	if s {
		if verbose {
			fmt.Fprintln(os.Stderr, "Mode: Source\nPort: "+strconv.Itoa(port)+"\nFile: "+filename)
		}

		ln, err := net.Listen("tcp", ":"+strconv.Itoa(port))
		if err != nil {
			os.Exit(1)
		}
		defer ln.Close()
		if verbose {
			fmt.Fprint(os.Stderr, "Waiting for connection... ")
		}
		conn, err := ln.Accept()
		if err != nil {
			os.Exit(1)
		}
		defer conn.Close()
		if verbose {
			fmt.Fprintln(os.Stderr, "connected from "+conn.RemoteAddr().String())
		}
		var f *os.File
		if filename == "-" {
			f = os.Stdin
		} else {
			f, err = os.Open(filename)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Error while file opening:", err)
				os.Exit(1)
			}
		}
		defer f.Close()
		fmt.Fprint(conn, "S")
		written, err := io.Copy(conn, f)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error while Copy:", err)
			os.Exit(1)
		}
		if verbose {
			fmt.Fprintln(os.Stderr, "Sent "+strconv.Itoa(int(written))+" bytes")
		}
	}
}

func Client() {
	hostname = flag.Arg(0)
	filename = flag.Arg(1)
	if port == -1 {
		port = 18000
	}
	if verbose {
		fmt.Fprintln(os.Stderr, "Client mode")
	}
	fmt.Fprintln(os.Stderr, "Port: "+strconv.Itoa(port)+"\nFile: "+filename)
	fmt.Fprint(os.Stderr, "Connecting... ")
	conn, err := net.Dial("tcp", hostname+":"+strconv.Itoa(port))
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error while file connecting:", err)
		os.Exit(1)
	}
	defer conn.Close()
	fmt.Fprintln(os.Stderr, "ok")
	mode := make([]byte, 1)
	conn.Read(mode)
	switch mode[0] {
	default:
		fmt.Fprintln(os.Stderr, "Unknown server mode")
		os.Exit(1)
	case 'D':
		var f *os.File
		if filename == "-" {
			f = os.Stdin
		} else {
			f, err = os.Open(filename)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Error while file open:", err)
				os.Exit(1)
			}
		}
		defer f.Close()
		fmt.Fprintln(os.Stderr, "Mode: Destination")
		io.Copy(conn, f)
	case 'S':
		var f *os.File
		if filename == "-" {
			f = os.Stdout
		} else {
			f, err = os.Create(filename)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Error while file creation:", err)
				os.Exit(1)
			}
		}
		defer f.Close()
		fmt.Fprintln(os.Stderr, "Mode: Source")
		io.Copy(f, conn)
	}
}

func main() {
	if d || s {
		Server()
	} else {
		Client()
	}
}
<|endoftext|>