<commit_before>package version

import (
	// Stdlib
	"fmt"

	// Internal
	"github.com/salsaflow/salsaflow/action"
	"github.com/salsaflow/salsaflow/errs"
	"github.com/salsaflow/salsaflow/git"
	"github.com/salsaflow/salsaflow/git/gitutil"
	"github.com/salsaflow/salsaflow/log"
	"github.com/salsaflow/salsaflow/scripts"
)

func GetByBranch(branch string) (ver *Version, err error) {
	// Remember the current branch.
	currentBranch, err := gitutil.CurrentBranch()
	if err != nil {
		return nil, err
	}

	// Checkout the target branch.
	if err := git.Checkout(branch); err != nil {
		return nil, err
	}
	defer func() {
		// Checkout the original branch on return.
		if ex := git.Checkout(currentBranch); ex != nil {
			if err == nil {
				err = ex
			} else {
				errs.Log(ex)
			}
		}
	}()

	// Get the version.
	v, err := Get()
	if err != nil {
		if ex, ok := err.(*scripts.ErrNotFound); ok {
			return nil, fmt.Errorf(
				"custom SalsaFlow script '%v' not found on branch '%v'", ex.ScriptName(), branch)
		}
		return nil, err
	}
	return v, nil
}

func SetForBranch(ver *Version, branch string) (act action.Action, err error) {
	var mainTask = fmt.Sprintf("Bump version to %v for branch '%v'", ver, branch)

	// Make sure the repository is clean (don't check untracked files).
	task := "Make sure the repository is clean"
	if err := git.EnsureCleanWorkingTree(false); err != nil {
		return nil, errs.NewError(task, err)
	}

	// Remember the current branch.
	currentBranch, err := gitutil.CurrentBranch()
	if err != nil {
		return nil, err
	}

	// Remember the current position of the target branch.
	task = fmt.Sprintf("Remember the position of branch '%v'", branch)
	originalPosition, err := git.Hexsha("refs/heads/" + branch)
	if err != nil {
		return nil, errs.NewError(task, err)
	}

	// Checkout the target branch.
	task = fmt.Sprintf("Checkout branch '%v'", branch)
	if err := git.Checkout(branch); err != nil {
		return nil, errs.NewError(task, err)
	}
	defer func() {
		// Checkout the original branch on return.
		task := fmt.Sprintf("Checkout branch '%v'", currentBranch)
		if ex := git.Checkout(currentBranch); ex != nil {
			if err == nil {
				err = ex
			} else {
				errs.LogError(task, ex)
			}
		}
	}()

	// Set the project version to the desired value.
	if err := Set(ver); err != nil {
		if ex, ok := err.(*scripts.ErrNotFound); ok {
			return nil, fmt.Errorf(
				"custom SalsaFlow script '%v' not found on branch '%v'", ex.ScriptName(), branch)
		}
		return nil, err
	}

	// Commit changes.
	_, err = git.RunCommand("commit", "-a",
		"-m", fmt.Sprintf("Bump version to %v", ver),
		"-m", fmt.Sprintf("Story-Id: %v", git.StoryIdUnassignedTagValue))
	if err != nil {
		task := "Reset the working tree to the original state"
		if err := git.Reset("--keep"); err != nil {
			errs.LogError(task, err)
		}
		return nil, err
	}

	return action.ActionFunc(func() (err error) {
		// On rollback, reset the target branch to the original position.
		log.Rollback(mainTask)
		return git.SetBranch(branch, originalPosition)
	}), nil
}
<commit_msg>version: Use reset --hard instead of --keep<commit_after>package version

import (
	// Stdlib
	"fmt"

	// Internal
	"github.com/salsaflow/salsaflow/action"
	"github.com/salsaflow/salsaflow/errs"
	"github.com/salsaflow/salsaflow/git"
	"github.com/salsaflow/salsaflow/git/gitutil"
	"github.com/salsaflow/salsaflow/log"
	"github.com/salsaflow/salsaflow/scripts"
)

func GetByBranch(branch string) (ver *Version, err error) {
	// Remember the current branch.
	currentBranch, err := gitutil.CurrentBranch()
	if err != nil {
		return nil, err
	}

	// Checkout the target branch.
	if err := git.Checkout(branch); err != nil {
		return nil, err
	}
	defer func() {
		// Checkout the original branch on return.
		if ex := git.Checkout(currentBranch); ex != nil {
			if err == nil {
				err = ex
			} else {
				errs.Log(ex)
			}
		}
	}()

	// Get the version.
	v, err := Get()
	if err != nil {
		if ex, ok := err.(*scripts.ErrNotFound); ok {
			return nil, fmt.Errorf(
				"custom SalsaFlow script '%v' not found on branch '%v'", ex.ScriptName(), branch)
		}
		return nil, err
	}
	return v, nil
}

func SetForBranch(ver *Version, branch string) (act action.Action, err error) {
	var mainTask = fmt.Sprintf("Bump version to %v for branch '%v'", ver, branch)

	// Make sure the repository is clean (don't check untracked files).
	task := "Make sure the repository is clean"
	if err := git.EnsureCleanWorkingTree(false); err != nil {
		return nil, errs.NewError(task, err)
	}

	// Remember the current branch.
	currentBranch, err := gitutil.CurrentBranch()
	if err != nil {
		return nil, err
	}

	// Remember the current position of the target branch.
	task = fmt.Sprintf("Remember the position of branch '%v'", branch)
	originalPosition, err := git.Hexsha("refs/heads/" + branch)
	if err != nil {
		return nil, errs.NewError(task, err)
	}

	// Checkout the target branch.
	task = fmt.Sprintf("Checkout branch '%v'", branch)
	if err := git.Checkout(branch); err != nil {
		return nil, errs.NewError(task, err)
	}
	defer func() {
		// Checkout the original branch on return.
		task := fmt.Sprintf("Checkout branch '%v'", currentBranch)
		if ex := git.Checkout(currentBranch); ex != nil {
			if err == nil {
				err = ex
			} else {
				errs.LogError(task, ex)
			}
		}
	}()

	// Set the project version to the desired value.
	if err := Set(ver); err != nil {
		if ex, ok := err.(*scripts.ErrNotFound); ok {
			return nil, fmt.Errorf(
				"custom SalsaFlow script '%v' not found on branch '%v'", ex.ScriptName(), branch)
		}
		return nil, err
	}

	// Commit changes.
	_, err = git.RunCommand("commit", "-a",
		"-m", fmt.Sprintf("Bump version to %v", ver),
		"-m", fmt.Sprintf("Story-Id: %v", git.StoryIdUnassignedTagValue))
	if err != nil {
		task := "Reset the working tree to the original state"
		if err := git.Reset("--hard"); err != nil {
			errs.LogError(task, err)
		}
		return nil, err
	}

	return action.ActionFunc(func() (err error) {
		// On rollback, reset the target branch to the original position.
		log.Rollback(mainTask)
		return git.SetBranch(branch, originalPosition)
	}), nil
}
<|endoftext|>


<commit_before>/*
 * boardgame-mysql-admin helps create and migrate sql databases for boardgame.
 */
package main

import (
	"database/sql"
	"errors"
	"flag"
	dsnparser "github.com/go-sql-driver/mysql"
	"github.com/jkomoros/boardgame/server/config"
	"github.com/mattes/migrate"
	"github.com/mattes/migrate/database/mysql"
	_ "github.com/mattes/migrate/source/file"
	"log"
	"os"
)

const (
	pathToMigrations = "$GOPATH/src/github.com/jkomoros/boardgame/storage/mysql/migrations/"
)

type appOptions struct {
	Help    bool
	flagSet *flag.FlagSet
}

func defineFlags(options *appOptions) {
	options.flagSet.BoolVar(&options.Help, "help", false, "If true, will print help and exit.")
}

func getOptions(flagSet *flag.FlagSet, flagArguments []string) *appOptions {
	options := &appOptions{flagSet: flagSet}
	defineFlags(options)
	flagSet.Parse(flagArguments)
	return options
}

func main() {
	flagSet := flag.CommandLine
	process(getOptions(flagSet, os.Args[1:]))
}

func process(options *appOptions) {

	if options.Help {
		log.Println("You asked for help!")
		return
	}

	path := os.ExpandEnv(pathToMigrations)

	if _, err := os.Stat(path); os.IsNotExist(err) {
		log.Println("The migrations path does not appear to exist")
		return
	}

	cfg, err := config.Get()

	if err != nil {
		log.Println("invalid config: " + err.Error())
		return
	}

	configToUse := cfg.Dev

	if configToUse.StorageConfig["mysql"] == "" {
		log.Println("No connection string configured for mysql")
		return
	}

	dsn, err := getDSN(configToUse.StorageConfig["mysql"])

	if err != nil {
		log.Println(err)
		return
	}

	db, _ := sql.Open("mysql", dsn)
	driver, _ := mysql.WithInstance(db, &mysql.Config{})
	m, err := migrate.NewWithDatabaseInstance(
		"file://"+path,
		"mysql",
		driver,
	)

	if err != nil {
		log.Println("Couldnt' create migration instance: " + err.Error())
		return
	}

	switch options.flagSet.Arg(0) {
	case "up":
		doUp(m)
	case "down":
		doDown(m)
	default:
		doVersion(m)
	}

}

func doUp(m *migrate.Migrate) {
	if err := m.Up(); err != nil {
		log.Println("Up failed: " + err.Error())
	}
}

func doDown(m *migrate.Migrate) {
	if err := m.Down(); err != nil {
		log.Println("Down failed: " + err.Error())
	}
}

func doVersion(m *migrate.Migrate) {
	version, _, _ := m.Version()
	log.Println("Version: ", version)
}

func getDSN(config string) (string, error) {

	//Substantially recreated in mysql/main.go

	parsedDSN, err := dsnparser.ParseDSN(config)

	if err != nil {
		return "", errors.New("config provided was not valid DSN: " + err.Error())
	}

	parsedDSN.Collation = "utf8mb4_unicode_ci"
	parsedDSN.MultiStatements = true

	return parsedDSN.FormatDSN(), nil
}
<commit_msg>Made the admin tool help message be a BIT more useful. Part of #273.<commit_after>/*
 * boardgame-mysql-admin helps create and migrate sql databases for boardgame.
 */
package main

import (
	"database/sql"
	"errors"
	"flag"
	dsnparser "github.com/go-sql-driver/mysql"
	"github.com/jkomoros/boardgame/server/config"
	"github.com/mattes/migrate"
	"github.com/mattes/migrate/database/mysql"
	_ "github.com/mattes/migrate/source/file"
	"log"
	"os"
)

const (
	pathToMigrations = "$GOPATH/src/github.com/jkomoros/boardgame/storage/mysql/migrations/"
)

type appOptions struct {
	Help    bool
	flagSet *flag.FlagSet
}

func defineFlags(options *appOptions) {
	options.flagSet.BoolVar(&options.Help, "help", false, "If true, will print help and exit.")
}

func getOptions(flagSet *flag.FlagSet, flagArguments []string) *appOptions {
	options := &appOptions{flagSet: flagSet}
	defineFlags(options)
	flagSet.Parse(flagArguments)
	return options
}

func main() {
	flagSet := flag.CommandLine
	process(getOptions(flagSet, os.Args[1:]))
}

func process(options *appOptions) {

	if options.Help {
		doHelp()
		return
	}

	path := os.ExpandEnv(pathToMigrations)

	if _, err := os.Stat(path); os.IsNotExist(err) {
		log.Println("The migrations path does not appear to exist")
		return
	}

	cfg, err := config.Get()

	if err != nil {
		log.Println("invalid config: " + err.Error())
		return
	}

	configToUse := cfg.Dev

	if configToUse.StorageConfig["mysql"] == "" {
		log.Println("No connection string configured for mysql")
		return
	}

	dsn, err := getDSN(configToUse.StorageConfig["mysql"])

	if err != nil {
		log.Println(err)
		return
	}

	db, _ := sql.Open("mysql", dsn)
	driver, _ := mysql.WithInstance(db, &mysql.Config{})
	m, err := migrate.NewWithDatabaseInstance(
		"file://"+path,
		"mysql",
		driver,
	)

	if err != nil {
		log.Println("Couldnt' create migration instance: " + err.Error())
		return
	}

	switch options.flagSet.Arg(0) {
	case "up":
		doUp(m)
	case "down":
		doDown(m)
	default:
		doVersion(m)
	}

}

func doHelp() {
	help := `Commands: 'version', 'up', 'down'`
	log.Println(help)
}

func doUp(m *migrate.Migrate) {
	if err := m.Up(); err != nil {
		log.Println("Up failed: " + err.Error())
	}
}

func doDown(m *migrate.Migrate) {
	if err := m.Down(); err != nil {
		log.Println("Down failed: " + err.Error())
	}
}

func doVersion(m *migrate.Migrate) {
	version, _, _ := m.Version()
	log.Println("Version: ", version)
}

func getDSN(config string) (string, error) {

	//Substantially recreated in mysql/main.go

	parsedDSN, err := dsnparser.ParseDSN(config)

	if err != nil {
		return "", errors.New("config provided was not valid DSN: " + err.Error())
	}

	parsedDSN.Collation = "utf8mb4_unicode_ci"
	parsedDSN.MultiStatements = true

	return parsedDSN.FormatDSN(), nil
}
<|endoftext|>


<commit_before>package system

import (
	"context"
	"fmt"
	"runtime"
	"sort"
	"text/tabwriter"
	"text/template"
	"time"

	"github.com/docker/cli/cli"
	"github.com/docker/cli/cli/command"
	"github.com/docker/cli/kubernetes"
	"github.com/docker/cli/templates"
	"github.com/docker/docker/api/types"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	kubernetesClient "k8s.io/client-go/kubernetes"
)

var versionTemplate = `{{with .Client -}}
Client:{{if ne .Platform.Name ""}} {{.Platform.Name}}{{end}}
 Version:	{{.Version}}
 API version:	{{.APIVersion}}{{if ne .APIVersion .DefaultAPIVersion}} (downgraded from {{.DefaultAPIVersion}}){{end}}
 Go version:	{{.GoVersion}}
 Git commit:	{{.GitCommit}}
 Built:	{{.BuildTime}}
 OS/Arch:	{{.Os}}/{{.Arch}}
 Experimental:	{{.Experimental}}
 Orchestrator:	{{.Orchestrator}}
{{- end}}

{{- if .ServerOK}}{{with .Server}}

Server:{{if ne .Platform.Name ""}} {{.Platform.Name}}{{end}}
 {{- range $component := .Components}}
 {{$component.Name}}:
  {{- if eq $component.Name "Engine" }}
  Version:	{{.Version}}
  API version:	{{index .Details "ApiVersion"}} (minimum version {{index .Details "MinAPIVersion"}})
  Go version:	{{index .Details "GoVersion"}}
  Git commit:	{{index .Details "GitCommit"}}
  Built:	{{index .Details "BuildTime"}}
  OS/Arch:	{{index .Details "Os"}}/{{index .Details "Arch"}}
  Experimental:	{{index .Details "Experimental"}}
  {{- else }}
  Version:	{{$component.Version}}
  {{- $detailsOrder := getDetailsOrder $component}}
  {{- range $key := $detailsOrder}}
  {{$key}}:		{{index $component.Details $key}}
   {{- end}}
  {{- end}}
 {{- end}}
 {{- end}}{{- end}}`

type versionOptions struct {
	format     string
	kubeConfig string
}

// versionInfo contains version information of both the Client, and Server
type versionInfo struct {
	Client clientVersion
	Server *types.Version
}

type clientVersion struct {
	Platform struct{ Name string } `json:",omitempty"`

	Version           string
	APIVersion        string `json:"ApiVersion"`
	DefaultAPIVersion string `json:"DefaultAPIVersion,omitempty"`
	GitCommit         string
	GoVersion         string
	Os                string
	Arch              string
	BuildTime         string `json:",omitempty"`
	Experimental      bool
	Orchestrator      string `json:",omitempty"`
}

type kubernetesVersion struct {
	Kubernetes string
	StackAPI   string
}

// ServerOK returns true when the client could connect to the docker server
// and parse the information received. It returns false otherwise.
func (v versionInfo) ServerOK() bool {
	return v.Server != nil
}

// NewVersionCommand creates a new cobra.Command for `docker version`
func NewVersionCommand(dockerCli command.Cli) *cobra.Command {
	var opts versionOptions

	cmd := &cobra.Command{
		Use:   "version [OPTIONS]",
		Short: "Show the Docker version information",
		Args:  cli.NoArgs,
		RunE: func(cmd *cobra.Command, args []string) error {
			return runVersion(dockerCli, &opts)
		},
	}

	flags := cmd.Flags()
	flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
	flags.StringVarP(&opts.kubeConfig, "kubeconfig", "k", "", "Kubernetes config file")
	flags.SetAnnotation("kubeconfig", "kubernetes", nil)
	flags.SetAnnotation("kubeconfig", "experimentalCLI", nil)

	return cmd
}

func reformatDate(buildTime string) string {
	t, errTime := time.Parse(time.RFC3339Nano, buildTime)
	if errTime == nil {
		return t.Format(time.ANSIC)
	}
	return buildTime
}

func runVersion(dockerCli command.Cli, opts *versionOptions) error {
	templateFormat := versionTemplate
	tmpl := templates.New("version")
	if opts.format != "" {
		templateFormat = opts.format
	} else {
		tmpl = tmpl.Funcs(template.FuncMap{"getDetailsOrder": getDetailsOrder})
	}

	var err error
	tmpl, err = tmpl.Parse(templateFormat)
	if err != nil {
		return cli.StatusError{StatusCode: 64,
			Status: "Template parsing error: " + err.Error()}
	}

	vd := versionInfo{
		Client: clientVersion{
			Platform:          struct{ Name string }{cli.PlatformName},
			Version:           cli.Version,
			APIVersion:        dockerCli.Client().ClientVersion(),
			DefaultAPIVersion: dockerCli.DefaultVersion(),
			GoVersion:         runtime.Version(),
			GitCommit:         cli.GitCommit,
			BuildTime:         reformatDate(cli.BuildTime),
			Os:                runtime.GOOS,
			Arch:              runtime.GOARCH,
			Experimental:      dockerCli.ClientInfo().HasExperimental,
			Orchestrator:      string(dockerCli.ClientInfo().Orchestrator),
		},
	}

	sv, err := dockerCli.Client().ServerVersion(context.Background())
	if err == nil {
		vd.Server = &sv
		kubeVersion := getKubernetesVersion(dockerCli, opts.kubeConfig)
		foundEngine := false
		foundKubernetes := false
		for _, component := range sv.Components {
			switch component.Name {
			case "Engine":
				foundEngine = true
				buildTime, ok := component.Details["BuildTime"]
				if ok {
					component.Details["BuildTime"] = reformatDate(buildTime)
				}
			case "Kubernetes":
				foundKubernetes = true
				if _, ok := component.Details["StackAPI"]; !ok && kubeVersion != nil {
					component.Details["StackAPI"] = kubeVersion.StackAPI
				}
			}
		}

		if !foundEngine {
			vd.Server.Components = append(vd.Server.Components, types.ComponentVersion{
				Name:    "Engine",
				Version: sv.Version,
				Details: map[string]string{
					"ApiVersion":    sv.APIVersion,
					"MinAPIVersion": sv.MinAPIVersion,
					"GitCommit":     sv.GitCommit,
					"GoVersion":     sv.GoVersion,
					"Os":            sv.Os,
					"Arch":          sv.Arch,
					"BuildTime":     reformatDate(vd.Server.BuildTime),
					"Experimental":  fmt.Sprintf("%t", sv.Experimental),
				},
			})
		}
		if !foundKubernetes && kubeVersion != nil {
			vd.Server.Components = append(vd.Server.Components, types.ComponentVersion{
				Name:    "Kubernetes",
				Version: kubeVersion.Kubernetes,
				Details: map[string]string{
					"StackAPI": kubeVersion.StackAPI,
				},
			})
		}
	}
	t := tabwriter.NewWriter(dockerCli.Out(), 15, 1, 1, ' ', 0)
	if err2 := tmpl.Execute(t, vd); err2 != nil && err == nil {
		err = err2
	}
	t.Write([]byte("\n"))
	t.Flush()
	return err
}

func getDetailsOrder(v types.ComponentVersion) []string {
	out := make([]string, 0, len(v.Details))
	for k := range v.Details {
		out = append(out, k)
	}
	sort.Strings(out)
	return out
}

func getKubernetesVersion(dockerCli command.Cli, kubeConfig string) *kubernetesVersion {
	if !dockerCli.ClientInfo().HasKubernetes() {
		return nil
	}

	version := kubernetesVersion{
		Kubernetes: "Unknown",
		StackAPI:   "Unknown",
	}
	clientConfig := kubernetes.NewKubernetesConfig(kubeConfig)
	config, err := clientConfig.ClientConfig()
	if err != nil {
		logrus.Debugf("failed to get Kubernetes configuration: %s", err)
		return &version
	}
	kubeClient, err := kubernetesClient.NewForConfig(config)
	if err != nil {
		logrus.Debugf("failed to get Kubernetes client: %s", err)
		return &version
	}
	version.StackAPI = getStackVersion(kubeClient)
	version.Kubernetes = getKubernetesServerVersion(kubeClient)
	return &version
}

func getStackVersion(client *kubernetesClient.Clientset) string {
	apiVersion, err := kubernetes.GetStackAPIVersion(client)
	if err != nil {
		logrus.Debugf("failed to get Stack API version: %s", err)
		return "Unknown"
	}
	return string(apiVersion)
}

func getKubernetesServerVersion(client *kubernetesClient.Clientset) string {
	kubeVersion, err := client.DiscoveryClient.ServerVersion()
	if err != nil {
		logrus.Debugf("failed to get Kubernetes server version: %s", err)
		return "Unknown"
	}
	return kubeVersion.String()
}
<commit_msg>Fix component information alignment<commit_after>package system

import (
	"context"
	"fmt"
	"runtime"
	"sort"
	"text/tabwriter"
	"text/template"
	"time"

	"github.com/docker/cli/cli"
	"github.com/docker/cli/cli/command"
	"github.com/docker/cli/kubernetes"
	"github.com/docker/cli/templates"
	"github.com/docker/docker/api/types"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	kubernetesClient "k8s.io/client-go/kubernetes"
)

var versionTemplate = `{{with .Client -}}
Client:{{if ne .Platform.Name ""}} {{.Platform.Name}}{{end}}
 Version:	{{.Version}}
 API version:	{{.APIVersion}}{{if ne .APIVersion .DefaultAPIVersion}} (downgraded from {{.DefaultAPIVersion}}){{end}}
 Go version:	{{.GoVersion}}
 Git commit:	{{.GitCommit}}
 Built:	{{.BuildTime}}
 OS/Arch:	{{.Os}}/{{.Arch}}
 Experimental:	{{.Experimental}}
 Orchestrator:	{{.Orchestrator}}
{{- end}}

{{- if .ServerOK}}{{with .Server}}

Server:{{if ne .Platform.Name ""}} {{.Platform.Name}}{{end}}
 {{- range $component := .Components}}
 {{$component.Name}}:
  {{- if eq $component.Name "Engine" }}
  Version:	{{.Version}}
  API version:	{{index .Details "ApiVersion"}} (minimum version {{index .Details "MinAPIVersion"}})
  Go version:	{{index .Details "GoVersion"}}
  Git commit:	{{index .Details "GitCommit"}}
  Built:	{{index .Details "BuildTime"}}
  OS/Arch:	{{index .Details "Os"}}/{{index .Details "Arch"}}
  Experimental:	{{index .Details "Experimental"}}
  {{- else }}
  Version:	{{$component.Version}}
  {{- $detailsOrder := getDetailsOrder $component}}
  {{- range $key := $detailsOrder}}
  {{$key}}:	{{index $component.Details $key}}
   {{- end}}
  {{- end}}
 {{- end}}
 {{- end}}{{- end}}`

type versionOptions struct {
	format     string
	kubeConfig string
}

// versionInfo contains version information of both the Client, and Server
type versionInfo struct {
	Client clientVersion
	Server *types.Version
}

type clientVersion struct {
	Platform struct{ Name string } `json:",omitempty"`

	Version           string
	APIVersion        string `json:"ApiVersion"`
	DefaultAPIVersion string `json:"DefaultAPIVersion,omitempty"`
	GitCommit         string
	GoVersion         string
	Os                string
	Arch              string
	BuildTime         string `json:",omitempty"`
	Experimental      bool
	Orchestrator      string `json:",omitempty"`
}

type kubernetesVersion struct {
	Kubernetes string
	StackAPI   string
}

// ServerOK returns true when the client could connect to the docker server
// and parse the information received. It returns false otherwise.
func (v versionInfo) ServerOK() bool {
	return v.Server != nil
}

// NewVersionCommand creates a new cobra.Command for `docker version`
func NewVersionCommand(dockerCli command.Cli) *cobra.Command {
	var opts versionOptions

	cmd := &cobra.Command{
		Use:   "version [OPTIONS]",
		Short: "Show the Docker version information",
		Args:  cli.NoArgs,
		RunE: func(cmd *cobra.Command, args []string) error {
			return runVersion(dockerCli, &opts)
		},
	}

	flags := cmd.Flags()
	flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
	flags.StringVarP(&opts.kubeConfig, "kubeconfig", "k", "", "Kubernetes config file")
	flags.SetAnnotation("kubeconfig", "kubernetes", nil)
	flags.SetAnnotation("kubeconfig", "experimentalCLI", nil)

	return cmd
}

func reformatDate(buildTime string) string {
	t, errTime := time.Parse(time.RFC3339Nano, buildTime)
	if errTime == nil {
		return t.Format(time.ANSIC)
	}
	return buildTime
}

func runVersion(dockerCli command.Cli, opts *versionOptions) error {
	templateFormat := versionTemplate
	tmpl := templates.New("version")
	if opts.format != "" {
		templateFormat = opts.format
	} else {
		tmpl = tmpl.Funcs(template.FuncMap{"getDetailsOrder": getDetailsOrder})
	}

	var err error
	tmpl, err = tmpl.Parse(templateFormat)
	if err != nil {
		return cli.StatusError{StatusCode: 64,
			Status: "Template parsing error: " + err.Error()}
	}

	vd := versionInfo{
		Client: clientVersion{
			Platform:          struct{ Name string }{cli.PlatformName},
			Version:           cli.Version,
			APIVersion:        dockerCli.Client().ClientVersion(),
			DefaultAPIVersion: dockerCli.DefaultVersion(),
			GoVersion:         runtime.Version(),
			GitCommit:         cli.GitCommit,
			BuildTime:         reformatDate(cli.BuildTime),
			Os:                runtime.GOOS,
			Arch:              runtime.GOARCH,
			Experimental:      dockerCli.ClientInfo().HasExperimental,
			Orchestrator:      string(dockerCli.ClientInfo().Orchestrator),
		},
	}

	sv, err := dockerCli.Client().ServerVersion(context.Background())
	if err == nil {
		vd.Server = &sv
		kubeVersion := getKubernetesVersion(dockerCli, opts.kubeConfig)
		foundEngine := false
		foundKubernetes := false
		for _, component := range sv.Components {
			switch component.Name {
			case "Engine":
				foundEngine = true
				buildTime, ok := component.Details["BuildTime"]
				if ok {
					component.Details["BuildTime"] = reformatDate(buildTime)
				}
			case "Kubernetes":
				foundKubernetes = true
				if _, ok := component.Details["StackAPI"]; !ok && kubeVersion != nil {
					component.Details["StackAPI"] = kubeVersion.StackAPI
				}
			}
		}

		if !foundEngine {
			vd.Server.Components = append(vd.Server.Components, types.ComponentVersion{
				Name:    "Engine",
				Version: sv.Version,
				Details: map[string]string{
					"ApiVersion":    sv.APIVersion,
					"MinAPIVersion": sv.MinAPIVersion,
					"GitCommit":     sv.GitCommit,
					"GoVersion":     sv.GoVersion,
					"Os":            sv.Os,
					"Arch":          sv.Arch,
					"BuildTime":     reformatDate(vd.Server.BuildTime),
					"Experimental":  fmt.Sprintf("%t", sv.Experimental),
				},
			})
		}
		if !foundKubernetes && kubeVersion != nil {
			vd.Server.Components = append(vd.Server.Components, types.ComponentVersion{
				Name:    "Kubernetes",
				Version: kubeVersion.Kubernetes,
				Details: map[string]string{
					"StackAPI": kubeVersion.StackAPI,
				},
			})
		}
	}
	t := tabwriter.NewWriter(dockerCli.Out(), 15, 1, 1, ' ', 0)
	if err2 := tmpl.Execute(t, vd); err2 != nil && err == nil {
		err = err2
	}
	t.Write([]byte("\n"))
	t.Flush()
	return err
}

func getDetailsOrder(v types.ComponentVersion) []string {
	out := make([]string, 0, len(v.Details))
	for k := range v.Details {
		out = append(out, k)
	}
	sort.Strings(out)
	return out
}

func getKubernetesVersion(dockerCli command.Cli, kubeConfig string) *kubernetesVersion {
	if !dockerCli.ClientInfo().HasKubernetes() {
		return nil
	}

	version := kubernetesVersion{
		Kubernetes: "Unknown",
		StackAPI:   "Unknown",
	}
	clientConfig := kubernetes.NewKubernetesConfig(kubeConfig)
	config, err := clientConfig.ClientConfig()
	if err != nil {
		logrus.Debugf("failed to get Kubernetes configuration: %s", err)
		return &version
	}
	kubeClient, err := kubernetesClient.NewForConfig(config)
	if err != nil {
		logrus.Debugf("failed to get Kubernetes client: %s", err)
		return &version
	}
	version.StackAPI = getStackVersion(kubeClient)
	version.Kubernetes = getKubernetesServerVersion(kubeClient)
	return &version
}

func getStackVersion(client *kubernetesClient.Clientset) string {
	apiVersion, err := kubernetes.GetStackAPIVersion(client)
	if err != nil {
		logrus.Debugf("failed to get Stack API version: %s", err)
		return "Unknown"
	}
	return string(apiVersion)
}

func getKubernetesServerVersion(client *kubernetesClient.Clientset) string {
	kubeVersion, err := client.DiscoveryClient.ServerVersion()
	if err != nil {
		logrus.Debugf("failed to get Kubernetes server version: %s", err)
		return "Unknown"
	}
	return kubeVersion.String()
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	version := "v1"
	if len(os.Args) > 1 {
		version = os.Args[1]
	}
	subtitle := os.Getenv("SUBTITLE")
	color := os.Getenv("COLOR")
	if len(color) == 0 {
		color = "#303030"
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, `<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Deployment Demonstration</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

%[1]s

%[2]s

`, version, subtitle, color)
	})

	http.HandleFunc("/_healthz", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "ok")
	})

	log.Printf("Listening on :8080 at %s ...", version)
	log.Fatal(http.ListenAndServe(":8080", nil))
}
<commit_msg>add func to instead of lengthiness parameters<commit_after>package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
)

var (
	version  string
	subtitle string
	color    string
)

const htmlContent = `<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Deployment Demonstration</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

%[1]s

%[2]s

`

func deploymentHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, htmlContent, version, subtitle, color)
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "ok")
}

func main() {
	version = "v1"
	if len(os.Args) > 1 {
		version = os.Args[1]
	}
	subtitle = os.Getenv("SUBTITLE")
	color = os.Getenv("COLOR")
	if len(color) == 0 {
		color = "#303030"
	}

	http.HandleFunc("/", deploymentHandler)

	http.HandleFunc("/_healthz", healthHandler)

	log.Printf("Listening on :8080 at %s ...", version)
	log.Fatal(http.ListenAndServe(":8080", nil))
}
<|endoftext|>


<commit_before>// Copyright 2016, RadiantBlue Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package client

import (
	"log"
	"time"

	piazza "github.com/venicegeo/pz-gocommon"
)

// implements Logger
type MockLoggerService struct {
	name    piazza.ServiceName
	address string
}

func NewMockLoggerService(sys *piazza.SystemConfig) (ILoggerService, error) {
	var _ piazza.IService = new(MockLoggerService)
	var _ ILoggerService = new(MockLoggerService)

	service := &MockLoggerService{name: "piazza.PzLogger", address: "0.0.0.0"}

	return service, nil
}

func (m *MockLoggerService) GetName() piazza.ServiceName {
	return m.name
}

func (m *MockLoggerService) GetAddress() string {
	return m.address
}

func (*MockLoggerService) GetFromMessages() ([]LogMessage, error) {
	return nil, nil
}

func (*MockLoggerService) GetFromAdminStats() (*LoggerAdminStats, error) {
	return &LoggerAdminStats{}, nil
}

func (*MockLoggerService) GetFromAdminSettings() (*LoggerAdminSettings, error) {
	return &LoggerAdminSettings{}, nil
}

func (*MockLoggerService) PostToAdminSettings(*LoggerAdminSettings) error {
	return nil
}

func (*MockLoggerService) LogMessage(mssg *LogMessage) error {
	tim := mssg.Time.Format("Jan _2 15:04:05")
	log.Printf("[%s, %s, %s, %s]", tim, mssg.Service, mssg.Severity, mssg.Message)
	return nil
}

func (mock *MockLoggerService) Log(service piazza.ServiceName, address string, severity Severity, t time.Time, message string, v ...interface{}) error {
	mssg := LogMessage{Service: service, Address: address, Severity: severity, Message: message, Time: t}
	return mock.LogMessage(&mssg)
}
<commit_msg>make mock client output unique<commit_after>// Copyright 2016, RadiantBlue Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package client

import (
	"log"
	"time"

	piazza "github.com/venicegeo/pz-gocommon"
)

// implements Logger
type MockLoggerService struct {
	name    piazza.ServiceName
	address string
}

func NewMockLoggerService(sys *piazza.SystemConfig) (ILoggerService, error) {
	var _ piazza.IService = new(MockLoggerService)
	var _ ILoggerService = new(MockLoggerService)

	service := &MockLoggerService{name: "piazza.PzLogger", address: "0.0.0.0"}

	return service, nil
}

func (m *MockLoggerService) GetName() piazza.ServiceName {
	return m.name
}

func (m *MockLoggerService) GetAddress() string {
	return m.address
}

func (*MockLoggerService) GetFromMessages() ([]LogMessage, error) {
	return nil, nil
}

func (*MockLoggerService) GetFromAdminStats() (*LoggerAdminStats, error) {
	return &LoggerAdminStats{}, nil
}

func (*MockLoggerService) GetFromAdminSettings() (*LoggerAdminSettings, error) {
	return &LoggerAdminSettings{}, nil
}

func (*MockLoggerService) PostToAdminSettings(*LoggerAdminSettings) error {
	return nil
}

func (*MockLoggerService) LogMessage(mssg *LogMessage) error {
	tim := mssg.Time.Format("Jan _2 15:04:05")
	log.Printf("[[%s, %s, %s, %s]]", tim, mssg.Service, mssg.Severity, mssg.Message)
	return nil
}

func (mock *MockLoggerService) Log(service piazza.ServiceName, address string, severity Severity, t time.Time, message string, v ...interface{}) error {
	mssg := LogMessage{Service: service, Address: address, Severity: severity, Message: message, Time: t}
	return mock.LogMessage(&mssg)
}
<|endoftext|>


<commit_before>// Copyright 2017 Vector Creations Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package routing

import (
	"net/http"

	"github.com/matrix-org/dendrite/clientapi/auth/authtypes"
	"github.com/matrix-org/dendrite/clientapi/httputil"
	roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
	"github.com/matrix-org/dendrite/userapi/api"
	"github.com/matrix-org/dendrite/userapi/storage/accounts"
	"github.com/matrix-org/gomatrixserverlib"
	"github.com/matrix-org/util"
)

func JoinRoomByIDOrAlias(
	req *http.Request,
	device *api.Device,
	rsAPI roomserverAPI.RoomserverInternalAPI,
	accountDB accounts.Database,
	roomIDOrAlias string,
) util.JSONResponse {
	// Prepare to ask the roomserver to perform the room join.
	joinReq := roomserverAPI.PerformJoinRequest{
		RoomIDOrAlias: roomIDOrAlias,
		UserID:        device.UserID,
		Content:       map[string]interface{}{},
	}
	joinRes := roomserverAPI.PerformJoinResponse{}

	// Check to see if any ?server_name= query parameters were
	// given in the request.
	if serverNames, ok := req.URL.Query()["server_name"]; ok {
		for _, serverName := range serverNames {
			joinReq.ServerNames = append(
				joinReq.ServerNames,
				gomatrixserverlib.ServerName(serverName),
			)
		}
	}

	// If content was provided in the request then include that
	// in the request. It'll get used as a part of the membership
	// event content.
	_ = httputil.UnmarshalJSONRequest(req, &joinReq.Content)

	// Work out our localpart for the client profile request.
	localpart, _, err := gomatrixserverlib.SplitID('@', device.UserID)
	if err != nil {
		util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
	} else {
		// Request our profile content to populate the request content with.
		var profile *authtypes.Profile
		profile, err = accountDB.GetProfileByLocalpart(req.Context(), localpart)
		if err != nil {
			util.GetLogger(req.Context()).WithError(err).Error("accountDB.GetProfileByLocalpart failed")
		} else {
			joinReq.Content["displayname"] = profile.DisplayName
			joinReq.Content["avatar_url"] = profile.AvatarURL
		}
	}

	// Ask the roomserver to perform the join.
	rsAPI.PerformJoin(req.Context(), &joinReq, &joinRes)
	if joinRes.Error != nil {
		return joinRes.Error.JSONResponse()
	}

	return util.JSONResponse{
		Code: http.StatusOK,
		// TODO: Put the response struct somewhere internal.
		JSON: struct {
			RoomID string `json:"room_id"`
		}{joinRes.RoomID},
	}
}
<commit_msg>Return 200 on join before time out (#1493)<commit_after>// Copyright 2017 Vector Creations Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package routing

import (
	"net/http"
	"time"

	"github.com/matrix-org/dendrite/clientapi/auth/authtypes"
	"github.com/matrix-org/dendrite/clientapi/httputil"
	"github.com/matrix-org/dendrite/clientapi/jsonerror"
	roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
	"github.com/matrix-org/dendrite/userapi/api"
	"github.com/matrix-org/dendrite/userapi/storage/accounts"
	"github.com/matrix-org/gomatrixserverlib"
	"github.com/matrix-org/util"
)

func JoinRoomByIDOrAlias(
	req *http.Request,
	device *api.Device,
	rsAPI roomserverAPI.RoomserverInternalAPI,
	accountDB accounts.Database,
	roomIDOrAlias string,
) util.JSONResponse {
	// Prepare to ask the roomserver to perform the room join.
	joinReq := roomserverAPI.PerformJoinRequest{
		RoomIDOrAlias: roomIDOrAlias,
		UserID:        device.UserID,
		Content:       map[string]interface{}{},
	}
	joinRes := roomserverAPI.PerformJoinResponse{}

	// Check to see if any ?server_name= query parameters were
	// given in the request.
	if serverNames, ok := req.URL.Query()["server_name"]; ok {
		for _, serverName := range serverNames {
			joinReq.ServerNames = append(
				joinReq.ServerNames,
				gomatrixserverlib.ServerName(serverName),
			)
		}
	}

	// If content was provided in the request then include that
	// in the request. It'll get used as a part of the membership
	// event content.
	_ = httputil.UnmarshalJSONRequest(req, &joinReq.Content)

	// Work out our localpart for the client profile request.
	localpart, _, err := gomatrixserverlib.SplitID('@', device.UserID)
	if err != nil {
		util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
	} else {
		// Request our profile content to populate the request content with.
		var profile *authtypes.Profile
		profile, err = accountDB.GetProfileByLocalpart(req.Context(), localpart)
		if err != nil {
			util.GetLogger(req.Context()).WithError(err).Error("accountDB.GetProfileByLocalpart failed")
		} else {
			joinReq.Content["displayname"] = profile.DisplayName
			joinReq.Content["avatar_url"] = profile.AvatarURL
		}
	}

	// Ask the roomserver to perform the join.
	done := make(chan util.JSONResponse, 1)
	go func() {
		defer close(done)
		rsAPI.PerformJoin(req.Context(), &joinReq, &joinRes)
		if joinRes.Error != nil {
			done <- joinRes.Error.JSONResponse()
		} else {
			done <- util.JSONResponse{
				Code: http.StatusOK,
				// TODO: Put the response struct somewhere internal.
				JSON: struct {
					RoomID string `json:"room_id"`
				}{joinRes.RoomID},
			}
		}
	}()

	// Wait either for the join to finish, or for us to hit a reasonable
	// timeout, at which point we'll just return a 200 to placate clients.
	select {
	case <-time.After(time.Second * 20):
		return util.JSONResponse{
			Code: http.StatusAccepted,
			JSON: jsonerror.Unknown("The room join will continue in the background."),
		}
	case result := <-done:
		return result
	}
}
<|endoftext|>


<commit_before>//go:build integration
// +build integration

/*
Copyright 2018 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package integration

import (
	"context"
	"fmt"
	"io"
	"net"
	"net/http"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
	"time"

	"k8s.io/apimachinery/pkg/util/wait"

	"github.com/pkg/errors"

	"k8s.io/minikube/pkg/kapi"
	"k8s.io/minikube/pkg/minikube/config"
	"k8s.io/minikube/pkg/util"
	"k8s.io/minikube/pkg/util/retry"
)

var tunnelSession StartSession

var (
	hostname = ""
	domain   = "nginx-svc.default.svc.cluster.local."
)

// validateTunnelCmd makes sure the minikube tunnel command works as expected
func validateTunnelCmd(ctx context.Context, t *testing.T, profile string) {
	ctx, cancel := context.WithTimeout(ctx, Minutes(20))
	type validateFunc func(context.Context, *testing.T, string)
	defer cancel()

	// Serial tests
	t.Run("serial", func(t *testing.T) {
		tests := []struct {
			name      string
			validator validateFunc
		}{
			{"StartTunnel", validateTunnelStart},                   // Start tunnel
			{"WaitService", validateServiceStable},                 // Wait for service is stable
			{"AccessDirect", validateAccessDirect},                 // Access test for loadbalancer IP
			{"DNSResolutionByDig", validateDNSDig},                 // DNS forwarding test by dig
			{"DNSResolutionByDscacheutil", validateDNSDscacheutil}, // DNS forwarding test by dscacheutil
			{"AccessThroughDNS", validateAccessDNS},                // Access test for absolute dns name
			{"DeleteTunnel", validateTunnelDelete},                 // Stop tunnel and delete cluster
		}
		for _, tc := range tests {
			tc := tc
			if ctx.Err() == context.DeadlineExceeded {
				t.Fatalf("Unable to run more tests (deadline exceeded)")
			}
			t.Run(tc.name, func(t *testing.T) {
				tc.validator(ctx, t, profile)
			})
		}
	})
}

// checkRoutePassword skips tunnel test if sudo password required for route
func checkRoutePassword(t *testing.T) {
	if !KicDriver() && runtime.GOOS != "windows" {
		if err := exec.Command("sudo", "-n", "ifconfig").Run(); err != nil {
			t.Skipf("password required to execute 'route', skipping testTunnel: %v", err)
		}
	}
}

// checkDNSForward skips DNS forwarding test if runtime is not supported
func checkDNSForward(t *testing.T) {
	// Not all platforms support DNS forwarding
	if runtime.GOOS != "darwin" || KicDriver() {
		t.Skip("DNS forwarding is only supported for hyprkit on darwin, skipping test DNS forwarding")
	}
}

// getKubeDNSIP returns kube-dns ClusterIP
func getKubeDNSIP(t *testing.T, profile string) string {
	// Load ClusterConfig
	c, err := config.Load(profile)
	if err != nil {
		t.Errorf("failed to load cluster config: %v", err)
	}
	// Get ipNet
	_, ipNet, err := net.ParseCIDR(c.KubernetesConfig.ServiceCIDR)
	if err != nil {
		t.Errorf("failed to parse service CIDR: %v", err)
	}
	// Get kube-dns ClusterIP
	ip, err := util.GetDNSIP(ipNet.String())
	if err != nil {
		t.Errorf("failed to get kube-dns IP: %v", err)
	}

	return ip.String()
}

// validateTunnelStart starts `minikube tunnel`
func validateTunnelStart(ctx context.Context, t *testing.T, profile string) {
	checkRoutePassword(t)

	args := []string{"-p", profile, "tunnel", "--alsologtostderr"}
	ss, err := Start(t, exec.CommandContext(ctx, Target(), args...))
	if err != nil {
		t.Errorf("failed to start a tunnel: args %q: %v", args, err)
	}
	tunnelSession = *ss
}

// validateServiceStable starts nginx pod, nginx service and waits nginx having loadbalancer ingress IP
func validateServiceStable(ctx context.Context, t *testing.T, profile string) {
	if GithubActionRunner() && runtime.GOOS == "darwin" {
		t.Skip("The test WaitService is broken on github actions in macos https://github.com/kubernetes/minikube/issues/8434")
	}
	checkRoutePassword(t)
	setupSucceeded := t.Run("Setup", func(t *testing.T) {
		client, err := kapi.Client(profile)
		if err != nil {
			t.Fatalf("failed to get Kubernetes client for %q: %v", profile, err)
		}

		// Start the "nginx" pod.
		rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "apply", "-f", filepath.Join(*testdataDir, "testsvc.yaml")))
		if err != nil {
			t.Fatalf("%s failed: %v", rr.Command(), err)
		}
		if _, err := PodWait(ctx, t, profile, "default", "run=nginx-svc", Minutes(4)); err != nil {
			t.Fatalf("wait: %v", err)
		}

		if err := kapi.WaitForService(client, "default", "nginx-svc", true, 1*time.Second, Minutes(2)); err != nil {
			t.Fatal(errors.Wrap(err, "Error waiting for nginx service to be up"))
		}
	})
	if !setupSucceeded {
		t.Fatal("Failed setup")
	}

	t.Run("IngressIP", func(t *testing.T) {
		if HyperVDriver() {
			t.Skip("The test WaitService/IngressIP is broken on hyperv https://github.com/kubernetes/minikube/issues/8381")
		}
		// Wait until the nginx-svc has a loadbalancer ingress IP
		err := wait.PollImmediate(5*time.Second, Minutes(3), func() (bool, error) {
			rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "svc", "nginx-svc", "-o", "jsonpath={.status.loadBalancer.ingress[0].ip}"))
			if err != nil {
				return false, err
			}
			if len(rr.Stdout.String()) > 0 {
				hostname = rr.Stdout.String()
				return true, nil
			}
			return false, nil
		})
		if err != nil {
			t.Errorf("nginx-svc svc.status.loadBalancer.ingress never got an IP: %v", err)
			rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "svc", "nginx-svc"))
			if err != nil {
				t.Errorf("%s failed: %v", rr.Command(), err)
			}
			t.Logf("failed to kubectl get svc nginx-svc:\n%s", rr.Output())
		}
	})
}

// validateAccessDirect validates if the test service can be accessed with LoadBalancer IP from host
func validateAccessDirect(ctx context.Context, t *testing.T, profile string) {
	if runtime.GOOS == "windows" {
		t.Skip("skipping: access direct test is broken on windows: https://github.com/kubernetes/minikube/issues/8304")
	}
	if GithubActionRunner() && runtime.GOOS == "darwin" {
		t.Skip("skipping: access direct test is broken on github actions on macos https://github.com/kubernetes/minikube/issues/8434")
	}

	checkRoutePassword(t)

	got := []byte{}
	url := fmt.Sprintf("http://%s", hostname)

	fetch := func() error {
		h := &http.Client{Timeout: time.Second * 10}
		resp, err := h.Get(url)
		if err != nil {
			return &retry.RetriableError{Err: err}
		}
		if resp.Body == nil {
			return &retry.RetriableError{Err: fmt.Errorf("no body")}
		}
		defer resp.Body.Close()
		got, err = io.ReadAll(resp.Body)
		if err != nil {
			return &retry.RetriableError{Err: err}
		}
		return nil
	}

	// Check if the nginx service can be accessed
	if err := retry.Expo(fetch, 3*time.Second, Minutes(2), 13); err != nil {
		t.Errorf("failed to hit nginx at %q: %v", url, err)

		rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "svc", "nginx-svc"))
		if err != nil {
			t.Errorf("%s failed: %v", rr.Command(), err)
		}
		t.Logf("failed to kubectl get svc nginx-svc:\n%s", rr.Stdout)
	}

	want := "Welcome to nginx!"
	if strings.Contains(string(got), want) {
		t.Logf("tunnel at %s is working!", url)
	} else {
		t.Errorf("expected body to contain %q, but got *%q*", want, got)
	}
}

// validateDNSDig validates if the DNS forwarding works by dig command DNS lookup
// NOTE: DNS forwarding is experimental: https://minikube.sigs.k8s.io/docs/handbook/accessing/#dns-resolution-experimental
func validateDNSDig(ctx context.Context, t *testing.T, profile string) {
	if GithubActionRunner() && runtime.GOOS == "darwin" {
		t.Skip("skipping: access direct test is broken on github actions on macos https://github.com/kubernetes/minikube/issues/8434")
	}

	checkRoutePassword(t)
	checkDNSForward(t)

	ip := getKubeDNSIP(t, profile)
	dnsIP := fmt.Sprintf("@%s", ip)

	// Check if the dig DNS lookup works toward kube-dns IP
	rr, err := Run(t, exec.CommandContext(ctx, "dig", "+time=5", "+tries=3", dnsIP, domain, "A"))
	// dig command returns its output for stdout only. So we don't check stderr output.
	if err != nil {
		t.Errorf("failed to resolve DNS name: %v", err)
	}

	want := "ANSWER: 1"
	if strings.Contains(rr.Stdout.String(), want) {
		t.Logf("DNS resolution by dig for %s is working!", domain)
	} else {
		t.Errorf("expected body to contain %q, but got *%q*", want, rr.Stdout.String())

		// debug DNS configuration
		rr, err := Run(t, exec.CommandContext(ctx, "scutil", "--dns"))
		if err != nil {
			t.Errorf("%s failed: %v", rr.Command(), err)
		}
		t.Logf("debug for DNS configuration:\n%s", rr.Stdout.String())
	}
}

// validateDNSDscacheutil validates if the DNS forwarding works by dscacheutil command DNS lookup
// NOTE: DNS forwarding is experimental: https://minikube.sigs.k8s.io/docs/handbook/accessing/#dns-resolution-experimental
func validateDNSDscacheutil(ctx context.Context, t *testing.T, profile string) {
	if GithubActionRunner() && runtime.GOOS == "darwin" {
		t.Skip("skipping: access direct test is broken on github actions on macos https://github.com/kubernetes/minikube/issues/8434")
	}

	checkRoutePassword(t)
	checkDNSForward(t)

	// Check if the dscacheutil DNS lookup works toward target domain
	rr, err := Run(t, exec.CommandContext(ctx, "dscacheutil", "-q", "host", "-a", "name", domain))
	// If dscacheutil cannot lookup dns record, it returns no output. So we don't check stderr output.
	if err != nil {
		t.Errorf("failed to resolve DNS name: %v", err)
	}

	want := hostname
	if strings.Contains(rr.Stdout.String(), want) {
		t.Logf("DNS resolution by dscacheutil for %s is working!", domain)
	} else {
		t.Errorf("expected body to contain %q, but got *%q*", want, rr.Stdout.String())
	}
}

// validateAccessDNS validates if the test service can be accessed with DNS forwarding from host
// NOTE: DNS forwarding is experimental: https://minikube.sigs.k8s.io/docs/handbook/accessing/#dns-resolution-experimental
func validateAccessDNS(ctx context.Context, t *testing.T, profile string) {
	if GithubActionRunner() && runtime.GOOS == "darwin" {
		t.Skip("skipping: access direct test is broken on github actions on macos https://github.com/kubernetes/minikube/issues/8434")
	}

	checkRoutePassword(t)
	checkDNSForward(t)

	got := []byte{}
	url := fmt.Sprintf("http://%s", domain)

	ip := getKubeDNSIP(t, profile)
	dnsIP := fmt.Sprintf("%s:53", ip)

	// Set kube-dns dial
	kubeDNSDial := func(ctx context.Context, network, address string) (net.Conn, error) {
		d := net.Dialer{}
		return d.DialContext(ctx, "udp", dnsIP)
	}

	// Set kube-dns resolver
	r := net.Resolver{
		PreferGo: true,
		Dial:     kubeDNSDial,
	}
	dialer := net.Dialer{Resolver: &r}

	// Use kube-dns resolver
	transport := &http.Transport{
		Dial:        dialer.Dial,
		DialContext: dialer.DialContext,
	}

	fetch := func() error {
		h := &http.Client{Timeout: time.Second * 10, Transport: transport}
		resp, err := h.Get(url)
		if err != nil {
			return &retry.RetriableError{Err: err}
		}
		if resp.Body == nil {
			return &retry.RetriableError{Err: fmt.Errorf("no body")}
		}
		defer resp.Body.Close()
		got, err = io.ReadAll(resp.Body)
		if err != nil {
			return &retry.RetriableError{Err: err}
		}
		return nil
	}

	// Access nginx-svc through DNS resolution
	if err := retry.Expo(fetch, 3*time.Second, Seconds(30), 10); err != nil {
		t.Errorf("failed to hit nginx with DNS forwarded %q: %v", url, err)
	}

	want := "Welcome to nginx!"
	if strings.Contains(string(got), want) {
		t.Logf("tunnel at %s is working!", url)
	} else {
		t.Errorf("expected body to contain %q, but got *%q*", want, got)
	}
}

// validateTunnelDelete stops `minikube tunnel`
func validateTunnelDelete(ctx context.Context, t *testing.T, profile string) {
	checkRoutePassword(t)
	// Stop tunnel
	tunnelSession.Stop(t)
}
<commit_msg>address review comment<commit_after>//go:build integration
// +build integration

/*
Copyright 2018 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package integration

import (
	"context"
	"fmt"
	"io"
	"net"
	"net/http"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
	"time"

	"k8s.io/apimachinery/pkg/util/wait"

	"github.com/pkg/errors"

	"k8s.io/minikube/pkg/kapi"
	"k8s.io/minikube/pkg/minikube/config"
	"k8s.io/minikube/pkg/util"
	"k8s.io/minikube/pkg/util/retry"
)

var tunnelSession StartSession

var (
	hostname = ""
	domain   = "nginx-svc.default.svc.cluster.local."
)

// validateTunnelCmd makes sure the minikube tunnel command works as expected
func validateTunnelCmd(ctx context.Context, t *testing.T, profile string) {
	ctx, cancel := context.WithTimeout(ctx, Minutes(20))
	type validateFunc func(context.Context, *testing.T, string)
	defer cancel()

	// Serial tests
	t.Run("serial", func(t *testing.T) {
		tests := []struct {
			name      string
			validator validateFunc
		}{
			{"StartTunnel", validateTunnelStart},                   // Start tunnel
			{"WaitService", validateServiceStable},                 // Wait for service is stable
			{"AccessDirect", validateAccessDirect},                 // Access test for loadbalancer IP
			{"DNSResolutionByDig", validateDNSDig},                 // DNS forwarding test by dig
			{"DNSResolutionByDscacheutil", validateDNSDscacheutil}, // DNS forwarding test by dscacheutil
			{"AccessThroughDNS", validateAccessDNS},                // Access test for absolute dns name
			{"DeleteTunnel", validateTunnelDelete},                 // Stop tunnel and delete cluster
		}
		for _, tc := range tests {
			tc := tc
			if ctx.Err() == context.DeadlineExceeded {
				t.Fatalf("Unable to run more tests (deadline exceeded)")
			}
			t.Run(tc.name, func(t *testing.T) {
				tc.validator(ctx, t, profile)
			})
		}
	})
}

// checkRoutePassword skips tunnel test if sudo password required for route
func checkRoutePassword(t *testing.T) {
	if !KicDriver() && runtime.GOOS != "windows" {
		if err := exec.Command("sudo", "-n", "ifconfig").Run(); err != nil {
			t.Skipf("password required to execute 'route', skipping testTunnel: %v", err)
		}
	}
}

// checkDNSForward skips DNS forwarding test if runtime is not supported
func checkDNSForward(t *testing.T) {
	// Not all platforms support DNS forwarding
	if runtime.GOOS != "darwin" || KicDriver() {
		t.Skip("DNS forwarding is only supported for Hyperkit on Darwin, skipping test DNS forwarding")
	}
}

// getKubeDNSIP returns kube-dns ClusterIP
func getKubeDNSIP(t *testing.T, profile string) string {
	// Load ClusterConfig
	c, err := config.Load(profile)
	if err != nil {
		t.Errorf("failed to load cluster config: %v", err)
	}
	// Get ipNet
	_, ipNet, err := net.ParseCIDR(c.KubernetesConfig.ServiceCIDR)
	if err != nil {
		t.Errorf("failed to parse service CIDR: %v", err)
	}
	// Get kube-dns ClusterIP
	ip, err := util.GetDNSIP(ipNet.String())
	if err != nil {
		t.Errorf("failed to get kube-dns IP: %v", err)
	}

	return ip.String()
}

// validateTunnelStart starts `minikube tunnel`
func validateTunnelStart(ctx context.Context, t *testing.T, profile string) {
	checkRoutePassword(t)

	args := []string{"-p", profile, "tunnel", "--alsologtostderr"}
	ss, err := Start(t, exec.CommandContext(ctx, Target(), args...))
	if err != nil {
		t.Errorf("failed to start a tunnel: args %q: %v", args, err)
	}
	tunnelSession = *ss
}

// validateServiceStable starts nginx pod, nginx service and waits nginx having loadbalancer ingress IP
func validateServiceStable(ctx context.Context, t *testing.T, profile string) {
	if GithubActionRunner() && runtime.GOOS == "darwin" {
		t.Skip("The test WaitService is broken on github actions in macos https://github.com/kubernetes/minikube/issues/8434")
	}
	checkRoutePassword(t)
	setupSucceeded := t.Run("Setup", func(t *testing.T) {
		client, err := kapi.Client(profile)
		if err != nil {
			t.Fatalf("failed to get Kubernetes client for %q: %v", profile, err)
		}

		// Start the "nginx" pod.
		rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "apply", "-f", filepath.Join(*testdataDir, "testsvc.yaml")))
		if err != nil {
			t.Fatalf("%s failed: %v", rr.Command(), err)
		}
		if _, err := PodWait(ctx, t, profile, "default", "run=nginx-svc", Minutes(4)); err != nil {
			t.Fatalf("wait: %v", err)
		}

		if err := kapi.WaitForService(client, "default", "nginx-svc", true, 1*time.Second, Minutes(2)); err != nil {
			t.Fatal(errors.Wrap(err, "Error waiting for nginx service to be up"))
		}
	})
	if !setupSucceeded {
		t.Fatal("Failed setup")
	}

	t.Run("IngressIP", func(t *testing.T) {
		if HyperVDriver() {
			t.Skip("The test WaitService/IngressIP is broken on hyperv https://github.com/kubernetes/minikube/issues/8381")
		}
		// Wait until the nginx-svc has a loadbalancer ingress IP
		err := wait.PollImmediate(5*time.Second, Minutes(3), func() (bool, error) {
			rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "svc", "nginx-svc", "-o", "jsonpath={.status.loadBalancer.ingress[0].ip}"))
			if err != nil {
				return false, err
			}
			if len(rr.Stdout.String()) > 0 {
				hostname = rr.Stdout.String()
				return true, nil
			}
			return false, nil
		})
		if err != nil {
			t.Errorf("nginx-svc svc.status.loadBalancer.ingress never got an IP: %v", err)
			rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "svc", "nginx-svc"))
			if err != nil {
				t.Errorf("%s failed: %v", rr.Command(), err)
			}
			t.Logf("failed to kubectl get svc nginx-svc:\n%s", rr.Output())
		}
	})
}

// validateAccessDirect validates if the test service can be accessed with LoadBalancer IP from host
func validateAccessDirect(ctx context.Context, t *testing.T, profile string) {
	if runtime.GOOS == "windows" {
		t.Skip("skipping: access direct test is broken on windows: https://github.com/kubernetes/minikube/issues/8304")
	}
	if GithubActionRunner() && runtime.GOOS == "darwin" {
		t.Skip("skipping: access direct test is broken on github actions on macos https://github.com/kubernetes/minikube/issues/8434")
	}

	checkRoutePassword(t)

	got := []byte{}
	url := fmt.Sprintf("http://%s", hostname)

	fetch := func() error {
		h := &http.Client{Timeout: time.Second * 10}
		resp, err := h.Get(url)
		if err != nil {
			return &retry.RetriableError{Err: err}
		}
		if resp.Body == nil {
			return &retry.RetriableError{Err: fmt.Errorf("no body")}
		}
		defer resp.Body.Close()
		got, err = io.ReadAll(resp.Body)
		if err != nil {
			return &retry.RetriableError{Err: err}
		}
		return nil
	}

	// Check if the nginx service can be accessed
	if err := retry.Expo(fetch, 3*time.Second, Minutes(2), 13); err != nil {
		t.Errorf("failed to hit nginx at %q: %v", url, err)

		rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "svc", "nginx-svc"))
		if err != nil {
			t.Errorf("%s failed: %v", rr.Command(), err)
		}
		t.Logf("failed to kubectl get svc nginx-svc:\n%s", rr.Stdout)
	}

	want := "Welcome to nginx!"
	if strings.Contains(string(got), want) {
		t.Logf("tunnel at %s is working!", url)
	} else {
		t.Errorf("expected body to contain %q, but got *%q*", want, got)
	}
}

// validateDNSDig validates if the DNS forwarding works by dig command DNS lookup
// NOTE: DNS forwarding is experimental: https://minikube.sigs.k8s.io/docs/handbook/accessing/#dns-resolution-experimental
func validateDNSDig(ctx context.Context, t *testing.T, profile string) {
	if GithubActionRunner() && runtime.GOOS == "darwin" {
		t.Skip("skipping: access direct test is broken on github actions on macos https://github.com/kubernetes/minikube/issues/8434")
	}

	checkRoutePassword(t)
	checkDNSForward(t)

	ip := getKubeDNSIP(t, profile)
	dnsIP := fmt.Sprintf("@%s", ip)

	// Check if the dig DNS lookup works toward kube-dns IP
	rr, err := Run(t, exec.CommandContext(ctx, "dig", "+time=5", "+tries=3", dnsIP, domain, "A"))
	// dig command returns its output for stdout only. So we don't check stderr output.
	if err != nil {
		t.Errorf("failed to resolve DNS name: %v", err)
	}

	want := "ANSWER: 1"
	if strings.Contains(rr.Stdout.String(), want) {
		t.Logf("DNS resolution by dig for %s is working!", domain)
	} else {
		t.Errorf("expected body to contain %q, but got *%q*", want, rr.Stdout.String())

		// debug DNS configuration
		rr, err := Run(t, exec.CommandContext(ctx, "scutil", "--dns"))
		if err != nil {
			t.Errorf("%s failed: %v", rr.Command(), err)
		}
		t.Logf("debug for DNS configuration:\n%s", rr.Stdout.String())
	}
}

// validateDNSDscacheutil validates if the DNS forwarding works by dscacheutil command DNS lookup
// NOTE: DNS forwarding is experimental: https://minikube.sigs.k8s.io/docs/handbook/accessing/#dns-resolution-experimental
func validateDNSDscacheutil(ctx context.Context, t *testing.T, profile string) {
	if GithubActionRunner() && runtime.GOOS == "darwin" {
		t.Skip("skipping: access direct test is broken on github actions on macos https://github.com/kubernetes/minikube/issues/8434")
	}

	checkRoutePassword(t)
	checkDNSForward(t)

	// Check if the dscacheutil DNS lookup works toward target domain
	rr, err := Run(t, exec.CommandContext(ctx, "dscacheutil", "-q", "host", "-a", "name", domain))
	// If dscacheutil cannot lookup dns record, it returns no output. So we don't check stderr output.
	if err != nil {
		t.Errorf("failed to resolve DNS name: %v", err)
	}

	want := hostname
	if strings.Contains(rr.Stdout.String(), want) {
		t.Logf("DNS resolution by dscacheutil for %s is working!", domain)
	} else {
		t.Errorf("expected body to contain %q, but got *%q*", want, rr.Stdout.String())
	}
}

// validateAccessDNS validates if the test service can be accessed with DNS forwarding from host
// NOTE: DNS forwarding is experimental: https://minikube.sigs.k8s.io/docs/handbook/accessing/#dns-resolution-experimental
func validateAccessDNS(ctx context.Context, t *testing.T, profile string) {
	if GithubActionRunner() && runtime.GOOS == "darwin" {
		t.Skip("skipping: access direct test is broken on github actions on macos https://github.com/kubernetes/minikube/issues/8434")
	}

	checkRoutePassword(t)
	checkDNSForward(t)

	got := []byte{}
	url := fmt.Sprintf("http://%s", domain)

	ip := getKubeDNSIP(t, profile)
	dnsIP := fmt.Sprintf("%s:53", ip)

	// Set kube-dns dial
	kubeDNSDial := func(ctx context.Context, network, address string) (net.Conn, error) {
		d := net.Dialer{}
		return d.DialContext(ctx, "udp", dnsIP)
	}

	// Set kube-dns resolver
	r := net.Resolver{
		PreferGo: true,
		Dial:     kubeDNSDial,
	}
	dialer := net.Dialer{Resolver: &r}

	// Use kube-dns resolver
	transport := &http.Transport{
		Dial:        dialer.Dial,
		DialContext: dialer.DialContext,
	}

	fetch := func() error {
		h := &http.Client{Timeout: time.Second * 10, Transport: transport}
		resp, err := h.Get(url)
		if err != nil {
			return &retry.RetriableError{Err: err}
		}
		if resp.Body == nil {
			return &retry.RetriableError{Err: fmt.Errorf("no body")}
		}
		defer resp.Body.Close()
		got, err = io.ReadAll(resp.Body)
		if err != nil {
			return &retry.RetriableError{Err: err}
		}
		return nil
	}

	// Access nginx-svc through DNS resolution
	if err := retry.Expo(fetch, 3*time.Second, Seconds(30), 10); err != nil {
		t.Errorf("failed to hit nginx with DNS forwarded %q: %v", url, err)
	}

	want := "Welcome to nginx!"
	if strings.Contains(string(got), want) {
		t.Logf("tunnel at %s is working!", url)
	} else {
		t.Errorf("expected body to contain %q, but got *%q*", want, got)
	}
}

// validateTunnelDelete stops `minikube tunnel`
func validateTunnelDelete(ctx context.Context, t *testing.T, profile string) {
	checkRoutePassword(t)
	// Stop tunnel
	tunnelSession.Stop(t)
}
<|endoftext|>


<commit_before>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"fmt"
	"github.com/jacobsa/aws/exp/sdb"
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/ogletest"
	"math/rand"
	"sync"
)

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

type integrationTest struct {
	db sdb.SimpleDB
}

func (t *integrationTest) SetUp(i *TestInfo) {
	var err error

	// Open a connection.
	t.db, err = sdb.NewSimpleDB(g_region, g_accessKey)
	AssertEq(nil, err)
}

// Generate an item name likely to be unique.
func (t *integrationTest) makeItemName() sdb.ItemName {
	return sdb.ItemName(fmt.Sprintf("item.%16x", uint64(rand.Int63())))
}

////////////////////////////////////////////////////////////////////////
// Domains
////////////////////////////////////////////////////////////////////////

var g_domainsTestDb sdb.SimpleDB
var g_domainsTestDomain0 sdb.Domain
var g_domainsTestDomain1 sdb.Domain

type DomainsTest struct {
	integrationTest

	mutex           sync.Mutex
	domainsToDelete []sdb.Domain  // Protected by mutex
}

func init() { RegisterTestSuite(&DomainsTest{}) }

func (t *DomainsTest) SetUpTestSuite() {
	var err error

	// Open a connection.
	g_domainsTestDb, err = sdb.NewSimpleDB(g_region, g_accessKey)
	if err != nil {
		panic(err)
	}

	// Create domain 0.
	g_domainsTestDomain0, err = g_domainsTestDb.OpenDomain("DomainsTest.domain0")
	if err != nil {
		panic(err)
	}

	// Create domain 1.
	g_domainsTestDomain1, err = g_domainsTestDb.OpenDomain("DomainsTest.domain1")
	if err != nil {
		panic(err)
	}
}

func (t *DomainsTest) TearDownTestSuite() {
	// Delete both domains.
	if err := g_domainsTestDb.DeleteDomain(g_domainsTestDomain0); err != nil {
		panic(err)
	}

	if err := g_domainsTestDb.DeleteDomain(g_domainsTestDomain1); err != nil {
		panic(err)
	}

	// Clear variables.
	g_domainsTestDb = nil
	g_domainsTestDomain0 = nil
	g_domainsTestDomain1 = nil
}

func (t *DomainsTest) TearDown() {
	t.mutex.Lock()
	defer t.mutex.Unlock()

	// Delete each of the domains created during the test.
	for _, d := range t.domainsToDelete {
		ExpectEq(nil, t.db.DeleteDomain(d), "Domain: %s", d.Name())
	}
}

func (t *DomainsTest) InvalidAccessKey() {
	// Open a connection with an unknown key ID.
	wrongKey := g_accessKey
	wrongKey.Id += "taco"

	db, err := sdb.NewSimpleDB(g_region, wrongKey)
	AssertEq(nil, err)

	// Attempt to create a domain.
	_, err = db.OpenDomain("some_domain")

	ExpectThat(err, Error(HasSubstr("403")))
	ExpectThat(err, Error(HasSubstr("Key Id")))
	ExpectThat(err, Error(HasSubstr("exist")))
}

func (t *DomainsTest) SeparatelyNamedDomainsHaveIndependentItems() {
	var err error

	// Set up an item in the first domain.
	itemName := t.makeItemName()
	err = g_domainsTestDomain0.PutAttributes(
		itemName,
		[]sdb.PutUpdate{
			sdb.PutUpdate{Name: "enchilada", Value: "queso"},
		},
		[]sdb.Precondition{},
	)

	AssertEq(nil, err)

	// Get attributes for the same name in the other domain. There should be
	// none.
	attrs, err := g_domainsTestDomain1.GetAttributes(itemName, true, []string{})
	AssertEq(nil, err)

	ExpectThat(attrs, ElementsAre())
}

func (t *DomainsTest) IdenticallyNamedDomainsHaveIdenticalItems() {
	var err error

	// Set up an item in the first domain.
	itemName := t.makeItemName()
	err = g_domainsTestDomain0.PutAttributes(
		itemName,
		[]sdb.PutUpdate{
			sdb.PutUpdate{Name: "enchilada", Value: "queso"},
		},
		[]sdb.Precondition{},
	)

	AssertEq(nil, err)

	// Get attributes for the same name in another domain object opened with the
	// same name.
	domain1, err := t.db.OpenDomain(g_domainsTestDomain0.Name())
	AssertEq(nil, err)

	attrs, err := domain1.GetAttributes(itemName, true, []string{})
	AssertEq(nil, err)

	ExpectThat(
		attrs,
		ElementsAre(
			DeepEquals(sdb.Attribute{Name: "enchilada", Value: "queso"}),
		),
	)
}

func (t *DomainsTest) Delete() {
	var err error
	domainName := "DomainsTest.Delete"

	// Create a domain, then delete it.
	domain, err := t.db.OpenDomain(domainName)
	AssertEq(nil, err)

	err = t.db.DeleteDomain(domain)
	AssertEq(nil, err)

	// Delete again; nothing should go wrong.
	err = t.db.DeleteDomain(domain)
	AssertEq(nil, err)

	// Attempt to write to the domain.
	err = domain.PutAttributes(
		"some_item",
		[]sdb.PutUpdate{
			sdb.PutUpdate{Name: "foo", Value: "bar"},
		},
		[]sdb.Precondition{},
	)

	ExpectThat(err, Error(HasSubstr("NoSuchDomain")))
	ExpectThat(err, Error(HasSubstr("domain")))
	ExpectThat(err, Error(HasSubstr("exist")))
}

////////////////////////////////////////////////////////////////////////
// Items
////////////////////////////////////////////////////////////////////////

var g_itemsTestDb     sdb.SimpleDB
var g_itemsTestDomain sdb.Domain

type ItemsTest struct {
	integrationTest
}

func init() { RegisterTestSuite(&ItemsTest{}) }

func (t *ItemsTest) SetUpTestSuite() {
	var err error

	// Open a connection.
	g_itemsTestDb, err = sdb.NewSimpleDB(g_region, g_accessKey)
	if err != nil {
		panic(err)
	}

	// Create a domain.
	g_itemsTestDomain, err = g_itemsTestDb.OpenDomain("ItemsTest.domain")
	if err != nil {
		panic(err)
	}
}

func (t *ItemsTest) TearDownTestSuite() {
	// Delete the domain.
	if err := g_itemsTestDb.DeleteDomain(g_itemsTestDomain); err != nil {
		panic(err)
	}

	// Clear variables.
	g_itemsTestDb = nil
	g_itemsTestDomain = nil
}

func (t *ItemsTest) InvalidUtf8ItemName() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) InvalidUtf8AttributeName() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) InvalidUtf8AttributeValue() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) LongItemName() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) LongAttributeName() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) LongAttributeValue() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) PutThenGet() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchPutThenGet() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchPutThenBatchGet() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) GetForNonExistentItem() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) GetParticularAttributes() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchGetParticularAttributes() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchGetForNonExistentItems() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) GetNonExistentAttributeName() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchGetNonExistentAttributeName() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) FailedValuePrecondition() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) FailedExistencePrecondition() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) FailedNonExistencePrecondition() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SuccessfulPreconditions() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) DeleteParticularAttributes() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) DeleteAllAttributes() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchDelete() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) InvalidSelectQuery() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectAll() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectItemName() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectCount() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectWithPredicates() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectWithSortOrder() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectWithLimit() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectEmptyResultSet() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectLargeResultSet() {
	ExpectEq("TODO", "")
}
<commit_msg>Deleted some redundant tests.<commit_after>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"fmt"
	"github.com/jacobsa/aws/exp/sdb"
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/ogletest"
	"math/rand"
	"sync"
)

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

type integrationTest struct {
	db sdb.SimpleDB
}

func (t *integrationTest) SetUp(i *TestInfo) {
	var err error

	// Open a connection.
	t.db, err = sdb.NewSimpleDB(g_region, g_accessKey)
	AssertEq(nil, err)
}

// Generate an item name likely to be unique.
func (t *integrationTest) makeItemName() sdb.ItemName {
	return sdb.ItemName(fmt.Sprintf("item.%16x", uint64(rand.Int63())))
}

////////////////////////////////////////////////////////////////////////
// Domains
////////////////////////////////////////////////////////////////////////

var g_domainsTestDb sdb.SimpleDB
var g_domainsTestDomain0 sdb.Domain
var g_domainsTestDomain1 sdb.Domain

type DomainsTest struct {
	integrationTest

	mutex           sync.Mutex
	domainsToDelete []sdb.Domain  // Protected by mutex
}

func init() { RegisterTestSuite(&DomainsTest{}) }

func (t *DomainsTest) SetUpTestSuite() {
	var err error

	// Open a connection.
	g_domainsTestDb, err = sdb.NewSimpleDB(g_region, g_accessKey)
	if err != nil {
		panic(err)
	}

	// Create domain 0.
	g_domainsTestDomain0, err = g_domainsTestDb.OpenDomain("DomainsTest.domain0")
	if err != nil {
		panic(err)
	}

	// Create domain 1.
	g_domainsTestDomain1, err = g_domainsTestDb.OpenDomain("DomainsTest.domain1")
	if err != nil {
		panic(err)
	}
}

func (t *DomainsTest) TearDownTestSuite() {
	// Delete both domains.
	if err := g_domainsTestDb.DeleteDomain(g_domainsTestDomain0); err != nil {
		panic(err)
	}

	if err := g_domainsTestDb.DeleteDomain(g_domainsTestDomain1); err != nil {
		panic(err)
	}

	// Clear variables.
	g_domainsTestDb = nil
	g_domainsTestDomain0 = nil
	g_domainsTestDomain1 = nil
}

func (t *DomainsTest) TearDown() {
	t.mutex.Lock()
	defer t.mutex.Unlock()

	// Delete each of the domains created during the test.
	for _, d := range t.domainsToDelete {
		ExpectEq(nil, t.db.DeleteDomain(d), "Domain: %s", d.Name())
	}
}

func (t *DomainsTest) InvalidAccessKey() {
	// Open a connection with an unknown key ID.
	wrongKey := g_accessKey
	wrongKey.Id += "taco"

	db, err := sdb.NewSimpleDB(g_region, wrongKey)
	AssertEq(nil, err)

	// Attempt to create a domain.
	_, err = db.OpenDomain("some_domain")

	ExpectThat(err, Error(HasSubstr("403")))
	ExpectThat(err, Error(HasSubstr("Key Id")))
	ExpectThat(err, Error(HasSubstr("exist")))
}

func (t *DomainsTest) SeparatelyNamedDomainsHaveIndependentItems() {
	var err error

	// Set up an item in the first domain.
	itemName := t.makeItemName()
	err = g_domainsTestDomain0.PutAttributes(
		itemName,
		[]sdb.PutUpdate{
			sdb.PutUpdate{Name: "enchilada", Value: "queso"},
		},
		[]sdb.Precondition{},
	)

	AssertEq(nil, err)

	// Get attributes for the same name in the other domain. There should be
	// none.
	attrs, err := g_domainsTestDomain1.GetAttributes(itemName, true, []string{})
	AssertEq(nil, err)

	ExpectThat(attrs, ElementsAre())
}

func (t *DomainsTest) IdenticallyNamedDomainsHaveIdenticalItems() {
	var err error

	// Set up an item in the first domain.
	itemName := t.makeItemName()
	err = g_domainsTestDomain0.PutAttributes(
		itemName,
		[]sdb.PutUpdate{
			sdb.PutUpdate{Name: "enchilada", Value: "queso"},
		},
		[]sdb.Precondition{},
	)

	AssertEq(nil, err)

	// Get attributes for the same name in another domain object opened with the
	// same name.
	domain1, err := t.db.OpenDomain(g_domainsTestDomain0.Name())
	AssertEq(nil, err)

	attrs, err := domain1.GetAttributes(itemName, true, []string{})
	AssertEq(nil, err)

	ExpectThat(
		attrs,
		ElementsAre(
			DeepEquals(sdb.Attribute{Name: "enchilada", Value: "queso"}),
		),
	)
}

func (t *DomainsTest) Delete() {
	var err error
	domainName := "DomainsTest.Delete"

	// Create a domain, then delete it.
	domain, err := t.db.OpenDomain(domainName)
	AssertEq(nil, err)

	err = t.db.DeleteDomain(domain)
	AssertEq(nil, err)

	// Delete again; nothing should go wrong.
	err = t.db.DeleteDomain(domain)
	AssertEq(nil, err)

	// Attempt to write to the domain.
	err = domain.PutAttributes(
		"some_item",
		[]sdb.PutUpdate{
			sdb.PutUpdate{Name: "foo", Value: "bar"},
		},
		[]sdb.Precondition{},
	)

	ExpectThat(err, Error(HasSubstr("NoSuchDomain")))
	ExpectThat(err, Error(HasSubstr("domain")))
	ExpectThat(err, Error(HasSubstr("exist")))
}

////////////////////////////////////////////////////////////////////////
// Items
////////////////////////////////////////////////////////////////////////

var g_itemsTestDb     sdb.SimpleDB
var g_itemsTestDomain sdb.Domain

type ItemsTest struct {
	integrationTest
}

func init() { RegisterTestSuite(&ItemsTest{}) }

func (t *ItemsTest) SetUpTestSuite() {
	var err error

	// Open a connection.
	g_itemsTestDb, err = sdb.NewSimpleDB(g_region, g_accessKey)
	if err != nil {
		panic(err)
	}

	// Create a domain.
	g_itemsTestDomain, err = g_itemsTestDb.OpenDomain("ItemsTest.domain")
	if err != nil {
		panic(err)
	}
}

func (t *ItemsTest) TearDownTestSuite() {
	// Delete the domain.
	if err := g_itemsTestDb.DeleteDomain(g_itemsTestDomain); err != nil {
		panic(err)
	}

	// Clear variables.
	g_itemsTestDb = nil
	g_itemsTestDomain = nil
}

func (t *ItemsTest) PutThenGet() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchPutThenGet() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchPutThenBatchGet() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) GetForNonExistentItem() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) GetParticularAttributes() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchGetParticularAttributes() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchGetForNonExistentItems() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) GetNonExistentAttributeName() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchGetNonExistentAttributeName() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) FailedValuePrecondition() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) FailedExistencePrecondition() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) FailedNonExistencePrecondition() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SuccessfulPreconditions() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) DeleteParticularAttributes() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) DeleteAllAttributes() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) BatchDelete() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) InvalidSelectQuery() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectAll() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectItemName() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectCount() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectWithPredicates() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectWithSortOrder() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectWithLimit() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectEmptyResultSet() {
	ExpectEq("TODO", "")
}

func (t *ItemsTest) SelectLargeResultSet() {
	ExpectEq("TODO", "")
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/bitly/go-simplejson"
	"github.com/codegangsta/cli"
	"github.com/modcloth/tory/tory"
)

var (
	usage = `populate tory inventory from Joyent listmachines json`
)

type joyentHostJSON struct {
	Name string `json:"name"`
	IP   string `json:"primaryIp"`

	Package string `json:"package,omitempty"`
	Image   string `json:"image,omitempty"`
	Type    string `json:"type,omitempty"`

	Disk   int `json:"disk,omitempty"`
	Memory int `json:"memory,omitempty"`

	Tags map[string]interface{} `json:"tags,omitempty"`
}

func main() {
	buildApp().Run(os.Args)
}

func buildApp() *cli.App {
	app := cli.NewApp()
	app.Name = "tory-sync-from-joyent"
	app.Usage = usage
	app.Version = "0.1.0"
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:   "s,tory-server",
			Value:  "http://localhost:9462/ansible/hosts",
			Usage:  "tory inventory server",
			EnvVar: "TORY_SERVER",
		},
		cli.StringFlag{
			Name:   "j,sdc-listmachines-json",
			Value:  "-",
			Usage:  "joyent listmachines input json",
			EnvVar: "TORY_SYNC_SDC_LISTMACHINES_JSON",
		},
	}
	app.Action = syncFromJoyent

	return app
}

func syncFromJoyent(c *cli.Context) {
	var (
		fd  io.Reader
		err error
	)

	server := c.String("tory-server")

	sj := c.String("sdc-listmachines-json")
	if sj == "-" {
		fd = os.Stdin
	} else {
		fd, err = os.Open(sj)
		if err != nil {
			log.Fatal(err.Error())
		}
	}

	sjJSON, err := simplejson.NewFromReader(fd)
	if err != nil {
		log.Fatal(err.Error())
	}

	i := 0
	for {
		j := sjJSON.GetIndex(i)
		if j == nil {
			break
		}

		if _, ok := j.CheckGet("name"); !ok {
			break
		}

		syncOneMachine(server, j)

		i++
	}

	log.Println("Ding!")
}

func syncOneMachine(server string, j *simplejson.Json) {
	hjJSONBytes, err := j.MarshalJSON()
	if err != nil {
		log.Fatal(err.Error())
	}

	jhj := &joyentHostJSON{
		Tags: map[string]interface{}{},
	}
	err = json.Unmarshal(hjJSONBytes, jhj)
	if err != nil {
		log.Fatal(err.Error())
	}

	hj := tory.NewHostJSON()
	hj.Name = jhj.Name
	hj.Package = jhj.Package
	hj.Image = jhj.Image
	hj.Type = jhj.Type
	hj.IP = jhj.IP
	for key, value := range jhj.Tags {
		hj.Tags[key] = fmt.Sprintf("%s", value)
	}
	hj.Vars["disk"] = fmt.Sprintf("%d", jhj.Disk)
	hj.Vars["memory"] = fmt.Sprintf("%d", jhj.Memory)

	hjBytes, err := json.Marshal(map[string]*tory.HostJSON{"host": hj})
	if err != nil {
		log.Fatal(err.Error())
	}

	buf := bytes.NewReader(hjBytes)
	resp, err := http.Post(server, "application/json", buf)
	if err != nil {
		log.Fatal(err.Error())
	}

	if resp.StatusCode != 201 {
		log.Printf("Failed to create host %v: %#v\n", hj.Name, resp.Status)
	} else {
		log.Printf("Added host %v\n", hj.Name)
	}
}
<commit_msg>Removing both simplejson and tory dependencies from joyenc sync thing<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	"github.com/codegangsta/cli"
)

var (
	usage = `populate tory inventory from Joyent listmachines json`
)

type joyentHostJSON struct {
	Name string `json:"name"`
	IP   string `json:"primaryIp"`

	Package string `json:"package,omitempty"`
	Image   string `json:"image,omitempty"`
	Type    string `json:"type,omitempty"`

	Disk   int `json:"disk,omitempty"`
	Memory int `json:"memory,omitempty"`

	Tags map[string]interface{} `json:"tags,omitempty"`
	Vars map[string]interface{} `json:"vars,omitempty"`
}

func main() {
	buildApp().Run(os.Args)
}

func buildApp() *cli.App {
	app := cli.NewApp()
	app.Name = "tory-sync-from-joyent"
	app.Usage = usage
	app.Version = "0.1.0"
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:   "s,tory-server",
			Value:  "http://localhost:9462/ansible/hosts",
			Usage:  "tory inventory server",
			EnvVar: "TORY_SERVER",
		},
		cli.StringFlag{
			Name:   "j,sdc-listmachines-json",
			Value:  "-",
			Usage:  "joyent listmachines input json",
			EnvVar: "TORY_SYNC_SDC_LISTMACHINES_JSON",
		},
	}
	app.Action = syncFromJoyent

	return app
}

func syncFromJoyent(c *cli.Context) {
	var (
		fd  io.Reader
		err error
	)

	server := c.String("tory-server")

	sj := c.String("sdc-listmachines-json")
	if sj == "-" {
		fd = os.Stdin
	} else {
		fd, err = os.Open(sj)
		if err != nil {
			log.Fatal(err.Error())
		}
	}

	sjBytes, err := ioutil.ReadAll(fd)
	if err != nil {
		log.Fatal(err.Error())
	}

	sjSlice := []*joyentHostJSON{}
	err = json.Unmarshal(sjBytes, &sjSlice)
	if err != nil {
		log.Fatal(err.Error())
	}

	for i := len(sjSlice) - 1; i >= 0; i-- {
		syncOneMachine(server, sjSlice[i])
	}

	log.Println("Ding!")
}

func syncOneMachine(server string, jhj *joyentHostJSON) {
	if jhj.Vars == nil {
		jhj.Vars = map[string]interface{}{}
	}

	jhj.Vars["disk"] = fmt.Sprintf("%d", jhj.Disk)
	jhj.Vars["memory"] = fmt.Sprintf("%d", jhj.Memory)

	jhjBytes, err := json.Marshal(map[string]*joyentHostJSON{"host": jhj})
	if err != nil {
		log.Fatal(err.Error())
	}

	buf := bytes.NewReader(jhjBytes)
	resp, err := http.Post(server, "application/json", buf)
	if err != nil {
		log.Fatal(err.Error())
	}

	if resp.StatusCode != 201 {
		log.Printf("Failed to create host %v: %#v\n", jhj.Name, resp.Status)
	} else {
		log.Printf("Added host %v\n", jhj.Name)
	}
}
<|endoftext|>


<commit_before>package mars

import (
	"github.com/agtorre/gocolorize"
	"github.com/robfig/config"
	"go/build"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"time"
)

const (
	MarsImportPath = "github.com/roblillack/mars"
)

type marsLogs struct {
	c gocolorize.Colorize
	w io.Writer
}

func (r *marsLogs) Write(p []byte) (n int, err error) {
	return r.w.Write([]byte(r.c.Paint(string(p))))
}

var (
	// App details
	AppName    string // e.g. "sample"
	AppRoot    string // e.g. "/app1"
	BasePath   string // e.g. "/Users/robfig/gocode/src/corp/sample"
	ImportPath string // e.g. "corp/sample"

	Config     *MergedConfig
	MimeConfig *MergedConfig
	RunMode    string // Application-defined (by default, "dev" or "prod")
	DevMode    bool   // if true, RunMode is a development mode.

	// Where to look for templates and configuration.
	// Ordered by priority.  (Earlier paths take precedence over later paths.)
	CodePaths []string
	ConfPaths []string

	// Server config.
	//
	// Alert: This is how the app is configured, which may be different from
	// the current process reality.  For example, if the app is configured for
	// port 9000, HttpPort will always be 9000, even though in dev mode it is
	// run on a random port and proxied.
	HttpPort    int    // e.g. 9000
	HttpAddr    string // e.g. "", "127.0.0.1"
	HttpSsl     bool   // e.g. true if using ssl
	HttpSslCert string // e.g. "/path/to/cert.pem"
	HttpSslKey  string // e.g. "/path/to/key.pem"

	// All cookies dropped by the framework begin with this prefix.
	CookiePrefix string
	// Cookie domain
	CookieDomain string
	// Cookie flags
	CookieHttpOnly bool
	CookieSecure   bool

	// Delimiters to use when rendering templates
	TemplateDelims string

	//Logger colors
	colors = map[string]gocolorize.Colorize{
		"trace": gocolorize.NewColor("magenta"),
		"info":  gocolorize.NewColor("green"),
		"warn":  gocolorize.NewColor("yellow"),
		"error": gocolorize.NewColor("red"),
	}

	error_log = marsLogs{c: colors["error"], w: os.Stderr}

	// Loggers
	TRACE = log.New(ioutil.Discard, "TRACE ", log.Ldate|log.Ltime|log.Lshortfile)
	INFO  = log.New(ioutil.Discard, "INFO  ", log.Ldate|log.Ltime|log.Lshortfile)
	WARN  = log.New(ioutil.Discard, "WARN  ", log.Ldate|log.Ltime|log.Lshortfile)
	ERROR = log.New(&error_log, "ERROR ", log.Ldate|log.Ltime|log.Lshortfile)

	MaxAge = time.Hour * 24 // MaxAge specifies the time browsers shall cache static content served using Static.Serve

	Initialized bool

	// Private
	secretKey []byte // Key used to sign cookies. An empty key disables signing.
)

func init() {
	log.SetFlags(INFO.Flags())
}

// InitDefaults initializes Mars based on runtime-loading of config files.
//
// Params:
//   mode - the run mode, which determines which app.conf settings are used.
//   basePath - the path to the configuration, messages, and view directories
func InitDefaults(mode, basePath string) {
	RunMode = mode

	if runtime.GOOS == "windows" {
		gocolorize.SetPlain(true)
	}

	BasePath = filepath.FromSlash(basePath)
	ConfPaths = []string{path.Join(BasePath, "conf")}

	/*
		fmt.Println("RunMode", RunMode)
		fmt.Println("BasePath", BasePath)
	*/

	// Load app.conf
	var err error
	Config, err = LoadConfig(path.Join(BasePath, "conf", "app.conf"))
	if err != nil || Config == nil {
		log.Fatalln("Failed to load app.conf:", err)
	}

	MimeConfig, _ = LoadConfig(path.Join(BasePath, "conf", "mime-types.conf"))

	// Ensure that the selected runmode appears in app.conf.
	// If empty string is passed as the mode, treat it as "DEFAULT"
	if mode == "" {
		mode = config.DEFAULT_SECTION
	}
	if !Config.HasSection(mode) {
		log.Fatalln("app.conf: No mode found:", mode)
	}
	Config.SetSection(mode)

	// Configure properties from app.conf
	DevMode = Config.BoolDefault("mode.dev", false)
	HttpPort = Config.IntDefault("http.port", 9000)
	HttpAddr = Config.StringDefault("http.addr", "")
	HttpSsl = Config.BoolDefault("http.ssl", false)
	HttpSslCert = Config.StringDefault("http.sslcert", "")
	HttpSslKey = Config.StringDefault("http.sslkey", "")
	if HttpSsl {
		if HttpSslCert == "" {
			log.Fatalln("No http.sslcert provided.")
		}
		if HttpSslKey == "" {
			log.Fatalln("No http.sslkey provided.")
		}
	}

	AppName = Config.StringDefault("app.name", "(not set)")
	AppRoot = Config.StringDefault("app.root", "")
	CookiePrefix = Config.StringDefault("cookie.prefix", "MARS")
	CookieDomain = Config.StringDefault("cookie.domain", "")
	CookieHttpOnly = Config.BoolDefault("cookie.httponly", false)
	CookieSecure = Config.BoolDefault("cookie.secure", false)
	TemplateDelims = Config.StringDefault("template.delimiters", "")
	if secretStr := Config.StringDefault("app.secret", ""); secretStr != "" {
		secretKey = []byte(secretStr)
	}

	// Configure logging
	if !Config.BoolDefault("log.colorize", true) {
		gocolorize.SetPlain(true)
	}

	TRACE = getLogger("trace")
	INFO = getLogger("info")
	WARN = getLogger("warn")
	ERROR = getLogger("error")

	MainTemplateLoader = NewTemplateLoader([]string{path.Join(BasePath, "views")})
	MainTemplateLoader.Refresh()

	Initialized = true
	INFO.Printf("Initialized Mars v%s (%s) for %s", VERSION, BUILD_DATE, MINIMUM_GO)
}

// Create a logger using log.* directives in app.conf plus the current settings
// on the default logger.
func getLogger(name string) *log.Logger {
	var logger *log.Logger

	// Create a logger with the requested output. (default to stderr)
	output := Config.StringDefault("log."+name+".output", "stderr")
	var newlog marsLogs

	switch output {
	case "stdout":
		newlog = marsLogs{c: colors[name], w: os.Stdout}
		logger = newLogger(&newlog)
	case "stderr":
		newlog = marsLogs{c: colors[name], w: os.Stderr}
		logger = newLogger(&newlog)
	default:
		if output == "off" {
			output = os.DevNull
		}

		file, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
		if err != nil {
			log.Fatalln("Failed to open log file", output, ":", err)
		}
		logger = newLogger(file)
	}

	// Set the prefix / flags.
	flags, found := Config.Int("log." + name + ".flags")
	if found {
		logger.SetFlags(flags)
	}

	prefix, found := Config.String("log." + name + ".prefix")
	if found {
		logger.SetPrefix(prefix)
	}

	return logger
}

func newLogger(wr io.Writer) *log.Logger {
	return log.New(wr, "", INFO.Flags())
}

// ResolveImportPath returns the filesystem path for the given import path.
// Returns an error if the import path could not be found.
func ResolveImportPath(importPath string) (string, error) {
	// GO15VENDOREXPERIMENT
	var err error
	var modPkg *build.Package
	for _, p := range []string{
		importPath,
		path.Join(ImportPath, "vendor", importPath),
		path.Join(MarsImportPath, "vendor", importPath)} {
		modPkg, err = build.Import(p, "", build.FindOnly)
		if err == nil {
			break
		}
	}

	if err != nil {
		return "", err
	}

	return modPkg.Dir, nil
}

func CheckInit() {
	if !Initialized {
		panic("Mars has not been initialized!")
	}
}
<commit_msg>Remove CodePaths, ConfPaths, ImportPath.<commit_after>package mars

import (
	"io"
	"io/ioutil"
	"log"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"time"

	"github.com/agtorre/gocolorize"
	"github.com/robfig/config"
)

const (
	MarsImportPath = "github.com/roblillack/mars"
)

type marsLogs struct {
	c gocolorize.Colorize
	w io.Writer
}

func (r *marsLogs) Write(p []byte) (n int, err error) {
	return r.w.Write([]byte(r.c.Paint(string(p))))
}

var (
	// App details
	AppName    string // e.g. "sample"
	AppRoot    string // e.g. "/app1"
	BasePath   string // e.g. "/Users/robfig/gocode/src/corp/sample"

	ConfigFile = path.Join("conf", "app.conf")

	Config     *MergedConfig
	MimeConfig *MergedConfig
	RunMode    string // Application-defined (by default, "dev" or "prod")
	DevMode    bool   // if true, RunMode is a development mode.

	// Server config.
	//
	// Alert: This is how the app is configured, which may be different from
	// the current process reality.  For example, if the app is configured for
	// port 9000, HttpPort will always be 9000, even though in dev mode it is
	// run on a random port and proxied.
	HttpPort    int    // e.g. 9000
	HttpAddr    string // e.g. "", "127.0.0.1"
	HttpSsl     bool   // e.g. true if using ssl
	HttpSslCert string // e.g. "/path/to/cert.pem"
	HttpSslKey  string // e.g. "/path/to/key.pem"

	// All cookies dropped by the framework begin with this prefix.
	CookiePrefix string
	// Cookie domain
	CookieDomain string
	// Cookie flags
	CookieHttpOnly bool
	CookieSecure   bool

	// Delimiters to use when rendering templates
	TemplateDelims string

	//Logger colors
	colors = map[string]gocolorize.Colorize{
		"trace": gocolorize.NewColor("magenta"),
		"info":  gocolorize.NewColor("green"),
		"warn":  gocolorize.NewColor("yellow"),
		"error": gocolorize.NewColor("red"),
	}

	error_log = marsLogs{c: colors["error"], w: os.Stderr}

	// Loggers
	TRACE = log.New(ioutil.Discard, "TRACE ", log.Ldate|log.Ltime|log.Lshortfile)
	INFO  = log.New(ioutil.Discard, "INFO  ", log.Ldate|log.Ltime|log.Lshortfile)
	WARN  = log.New(ioutil.Discard, "WARN  ", log.Ldate|log.Ltime|log.Lshortfile)
	ERROR = log.New(&error_log, "ERROR ", log.Ldate|log.Ltime|log.Lshortfile)

	MaxAge = time.Hour * 24 // MaxAge specifies the time browsers shall cache static content served using Static.Serve

	Initialized bool

	// Private
	secretKey []byte // Key used to sign cookies. An empty key disables signing.
)

func init() {
	log.SetFlags(INFO.Flags())
}

// InitDefaults initializes Mars based on runtime-loading of config files.
//
// Params:
//   mode - the run mode, which determines which app.conf settings are used.
//   basePath - the path to the configuration, messages, and view directories
func InitDefaults(mode, basePath string) {
	RunMode = mode

	if runtime.GOOS == "windows" {
		gocolorize.SetPlain(true)
	}

	BasePath = filepath.FromSlash(basePath)

	// Load app.conf
	var err error
	Config, err = LoadConfig(path.Join(BasePath, ConfigFile))
	if err != nil || Config == nil {
		log.Fatalln("Failed to load app.conf:", err)
	}

	MimeConfig, _ = LoadConfig(path.Join(BasePath, "conf", "mime-types.conf"))

	// Ensure that the selected runmode appears in app.conf.
	// If empty string is passed as the mode, treat it as "DEFAULT"
	if mode == "" {
		mode = config.DEFAULT_SECTION
	}
	if !Config.HasSection(mode) {
		log.Fatalln("app.conf: No mode found:", mode)
	}
	Config.SetSection(mode)

	// Configure properties from app.conf
	DevMode = Config.BoolDefault("mode.dev", false)
	HttpPort = Config.IntDefault("http.port", 9000)
	HttpAddr = Config.StringDefault("http.addr", "")
	HttpSsl = Config.BoolDefault("http.ssl", false)
	HttpSslCert = Config.StringDefault("http.sslcert", "")
	HttpSslKey = Config.StringDefault("http.sslkey", "")
	if HttpSsl {
		if HttpSslCert == "" {
			log.Fatalln("No http.sslcert provided.")
		}
		if HttpSslKey == "" {
			log.Fatalln("No http.sslkey provided.")
		}
	}

	AppName = Config.StringDefault("app.name", "(not set)")
	AppRoot = Config.StringDefault("app.root", "")
	CookiePrefix = Config.StringDefault("cookie.prefix", "MARS")
	CookieDomain = Config.StringDefault("cookie.domain", "")
	CookieHttpOnly = Config.BoolDefault("cookie.httponly", false)
	CookieSecure = Config.BoolDefault("cookie.secure", false)
	TemplateDelims = Config.StringDefault("template.delimiters", "")
	if secretStr := Config.StringDefault("app.secret", ""); secretStr != "" {
		secretKey = []byte(secretStr)
	}

	// Configure logging
	if !Config.BoolDefault("log.colorize", true) {
		gocolorize.SetPlain(true)
	}

	TRACE = getLogger("trace")
	INFO = getLogger("info")
	WARN = getLogger("warn")
	ERROR = getLogger("error")

	MainTemplateLoader = NewTemplateLoader([]string{path.Join(BasePath, "views")})
	MainTemplateLoader.Refresh()

	Initialized = true
	INFO.Printf("Initialized Mars v%s (%s) for %s", VERSION, BUILD_DATE, MINIMUM_GO)
}

// Create a logger using log.* directives in app.conf plus the current settings
// on the default logger.
func getLogger(name string) *log.Logger {
	var logger *log.Logger

	// Create a logger with the requested output. (default to stderr)
	output := Config.StringDefault("log."+name+".output", "stderr")
	var newlog marsLogs

	switch output {
	case "stdout":
		newlog = marsLogs{c: colors[name], w: os.Stdout}
		logger = newLogger(&newlog)
	case "stderr":
		newlog = marsLogs{c: colors[name], w: os.Stderr}
		logger = newLogger(&newlog)
	default:
		if output == "off" {
			output = os.DevNull
		}

		file, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
		if err != nil {
			log.Fatalln("Failed to open log file", output, ":", err)
		}
		logger = newLogger(file)
	}

	// Set the prefix / flags.
	flags, found := Config.Int("log." + name + ".flags")
	if found {
		logger.SetFlags(flags)
	}

	prefix, found := Config.String("log." + name + ".prefix")
	if found {
		logger.SetPrefix(prefix)
	}

	return logger
}

func newLogger(wr io.Writer) *log.Logger {
	return log.New(wr, "", INFO.Flags())
}

// ResolveImportPath returns the filesystem path for the given import path.
// Returns an error if the import path could not be found.
func ResolveImportPath(importPath string) (string, error) {
	// GO15VENDOREXPERIMENT
	var err error
	var modPkg *build.Package
	for _, p := range []string{
		importPath,
		path.Join(ImportPath, "vendor", importPath),
		path.Join(MarsImportPath, "vendor", importPath)} {
		modPkg, err = build.Import(p, "", build.FindOnly)
		if err == nil {
			break
		}
	}

	if err != nil {
		return "", err
	}

	return modPkg.Dir, nil
}

func CheckInit() {
	if !Initialized {
		panic("Mars has not been initialized!")
	}
}
<|endoftext|>