// composeUp converts given json to yaml, saves to a file on the host and
// uses `docker-compose up -d` to create the containers.
func composeUp(d driver.DistroDriver, json map[string]interface{}) error {
	if len(json) == 0 {
		log.Println("docker-compose config not specified, noop")
		return nil
	}

	// Convert json to yaml
	yaml, err := yaml.Marshal(json)
	if err != nil {
		return fmt.Errorf("error converting to compose.yml: %v", err)
	}

	if err := os.MkdirAll(composeYmlDir, 0777); err != nil {
		return fmt.Errorf("failed creating %s: %v", composeYmlDir, err)
	}
	log.Printf("Using compose yaml:>>>>>\n%s\n<<<<<", string(yaml))
	ymlPath := filepath.Join(composeYmlDir, composeYml)
	if err := ioutil.WriteFile(ymlPath, yaml, 0666); err != nil {
		return fmt.Errorf("error writing %s: %v", ymlPath, err)
	}

	// set timeout for docker-compose -> docker-engine interactions.
	// When downloading large images, docker-compose intermittently times out
	// (gh#docker/compose/issues/2186).
	os.Setenv("COMPOSE_HTTP_TIMEOUT", fmt.Sprintf("%d", composeTimeoutSecs))  // versions <= 1.4.2
	os.Setenv("DOCKER_CLIENT_TIMEOUT", fmt.Sprintf("%d", composeTimeoutSecs)) // version  >= 1.5.0
	defer os.Unsetenv("COMPOSE_HTTP_TIMEOUT")
	defer os.Unsetenv("DOCKER_CLIENT_TIMEOUT")

	return executil.ExecPipeToFds(executil.Fds{Out: ioutil.Discard}, composeBinPath(d), "-p", composeProject, "-f", ymlPath, "up", "-d")
}
Exemplo n.º 2
0
Arquivo: main.go Projeto: Jdesk/os
func main(cfg *config.CloudConfig) error {
	os.Unsetenv("_LIBCONTAINER_INITPIPE")
	os.Unsetenv("_LIBCONTAINER_INITPID")

	if err := system.ParentDeathSignal(syscall.SIGKILL).Set(); err != nil {
		return err
	}

	if err := os.Remove("/var/run/docker.pid"); err != nil && !os.IsNotExist(err) {
		return err
	}

	dockerCfg := cfg.Rancher.Docker

	args := dockerCfg.FullArgs()

	log.Debugf("User Docker args: %v", args)

	if dockerCfg.TLS {
		log.Debug("Generating TLS certs if needed")
		if err := control.Generate(true, "/etc/docker/tls", []string{"localhost"}); err != nil {
			return err
		}
	}

	prog := findProgram("docker-init", "dockerlaunch", "docker")
	if strings.Contains(prog, "dockerlaunch") {
		args = append([]string{prog, "docker"}, args...)
	} else {
		args = append([]string{prog}, args...)
	}

	log.Infof("Running %v", args)
	return syscall.Exec(args[0], args, dockerCfg.AppendEnv())
}
Exemplo n.º 3
0
func TestNewCliParamsFromEnvVarsWithRegionSpecifiedAsEnvVariable(t *testing.T) {
	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalContext := cli.NewContext(nil, globalSet, nil)
	context := cli.NewContext(nil, nil, globalContext)
	rdwr := &mockReadWriter{}

	os.Setenv("AWS_REGION", "us-west-1")
	os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
	os.Setenv("AWS_SECRET_KEY", "SECRET")
	defer func() {
		os.Unsetenv("AWS_REGION")
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
	}()

	params, err := NewCliParams(context, rdwr)
	if err != nil {
		t.Errorf("Unexpected error when region is specified using environment variable AWS_REGION: ", err)
	}

	paramsRegion := aws.StringValue(params.Config.Region)
	if "us-west-1" != paramsRegion {
		t.Errorf("Unexpected region set, expected: us-west-1, got: %s", paramsRegion)
	}
}
Exemplo n.º 4
0
func (s *S) TestShellToContainerWithUnit(c *check.C) {
	guesser := cmdtest.FakeGuesser{Name: "myapp"}
	server := httptest.NewServer(buildHandler([]byte("hello my friend\nglad to see you here\n")))
	defer server.Close()
	target := "http://" + server.Listener.Addr().String()
	os.Setenv("TSURU_TARGET", target)
	defer os.Unsetenv("TSURU_TARGET")
	os.Setenv("TSURU_TOKEN", "abc123")
	defer os.Unsetenv("TSURU_TOKEN")
	var stdout, stderr, stdin bytes.Buffer
	context := Context{
		Args:   []string{"containerid"},
		Stdout: &stdout,
		Stderr: &stderr,
		Stdin:  &stdin,
	}
	var command ShellToContainerCmd
	command.GuessingCommand = GuessingCommand{G: &guesser}
	err := command.Flags().Parse(true, []string{"-a", "myapp"})
	c.Assert(err, check.IsNil)
	mngr := NewManager("admin", "0.1", "admin-ver", &stdout, &stderr, nil, nil)
	client := NewClient(http.DefaultClient, &context, mngr)
	err = command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(stdout.String(), check.Equals, "hello my friend\nglad to see you here\n")
}
Exemplo n.º 5
0
// TestRuntime tests stuff from runtime.go
func TestRuntime(t *testing.T) {
	Convey("The Runtime configuration tests, ", t, func() {
		envvars := []string{"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_STORAGE_BUCKET_NAME", "REDIS_URL"}
		for i := range envvars {
			envvar := envvars[i]
			Convey(fmt.Sprintf("Without %s", envvar), func() {
				curVal := os.Getenv(envvar)
				os.Unsetenv(envvar)
				So(func() { CheckEnvVars() }, ShouldPanic)
				os.Setenv(envvar, curVal)
			})
		}

		Convey("Without MAX_CPUS", func() {
			envvar := "MAX_CPUS"
			curVal := os.Getenv(envvar)
			os.Unsetenv(envvar)
			So(func() { ConfigureRuntime() }, ShouldNotPanic)
			os.Setenv(envvar, curVal)
		})

		invalidLogLevels := []string{"D3BUG", ""}
		for i := range invalidLogLevels {
			envvar := "LOG_LEVEL"
			envval := invalidLogLevels[i]
			Convey(fmt.Sprintf("With %s to %s", envvar, envval), func() {
				curVal := os.Getenv(envvar)
				os.Setenv(envvar, envval)
				So(func() { ConfigureLogger() }, ShouldNotPanic)
				os.Setenv(envvar, curVal)
			})
		}
	})
}
Exemplo n.º 6
0
func TestPopulateContext(t *testing.T) {
	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalContext := cli.NewContext(nil, globalSet, nil)
	cliContext := cli.NewContext(nil, nil, globalContext)
	ecsContext := &ecscompose.Context{}

	// Create a temprorary directory for the dummy ecs config
	tempDirName, err := ioutil.TempDir("", "test")
	if err != nil {
		t.Fatal("Error while creating the dummy ecs config directory")
	}
	defer os.Remove(tempDirName)
	os.Setenv("HOME", tempDirName)

	os.Setenv("AWS_REGION", "us-east-1")
	os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
	os.Setenv("AWS_SECRET_KEY", "secret")
	defer func() {
		os.Unsetenv("AWS_REGION")
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
		os.Unsetenv("HOME")
	}()

	projectFactory := projectFactory{}
	err = projectFactory.populateContext(ecsContext, cliContext)

	if err != nil {
		t.Fatal("Error while populating the context")
	}

	if ecsContext.ECSParams == nil {
		t.Error("ECS Params was expected to be set for ecsContext but was nil")
	}
}
Exemplo n.º 7
0
// unsetEnv unsets enviornment variables for testing a "clean slate" with no
// credentials in the environment
func unsetEnv(t *testing.T) func() {
	// Grab any existing AWS keys and preserve. In some tests we'll unset these, so
	// we need to have them and restore them after
	e := getEnv()
	if err := os.Unsetenv("AWS_ACCESS_KEY_ID"); err != nil {
		t.Fatalf("Error unsetting env var AWS_ACCESS_KEY_ID: %s", err)
	}
	if err := os.Unsetenv("AWS_SECRET_ACCESS_KEY"); err != nil {
		t.Fatalf("Error unsetting env var AWS_SECRET_ACCESS_KEY: %s", err)
	}
	if err := os.Unsetenv("AWS_SESSION_TOKEN"); err != nil {
		t.Fatalf("Error unsetting env var AWS_SESSION_TOKEN: %s", err)
	}

	return func() {
		// re-set all the envs we unset above
		if err := os.Setenv("AWS_ACCESS_KEY_ID", e.Key); err != nil {
			t.Fatalf("Error resetting env var AWS_ACCESS_KEY_ID: %s", err)
		}
		if err := os.Setenv("AWS_SECRET_ACCESS_KEY", e.Secret); err != nil {
			t.Fatalf("Error resetting env var AWS_SECRET_ACCESS_KEY: %s", err)
		}
		if err := os.Setenv("AWS_SESSION_TOKEN", e.Token); err != nil {
			t.Fatalf("Error resetting env var AWS_SESSION_TOKEN: %s", err)
		}
	}
}
Exemplo n.º 8
0
// Test - Bitrise Validate workflow
// Workflow contains before and after workflow, and no one contains steps, but circular wofklow dependecy exist, which should fail
func Test0Steps3WorkflowsCircularDependency(t *testing.T) {
	require.NoError(t, os.Setenv("BITRISE_BUILD_STATUS", "0"))
	defer func() { require.NoError(t, os.Unsetenv("BITRISE_BUILD_STATUS")) }()

	require.NoError(t, os.Setenv("STEPLIB_BUILD_STATUS", "0"))
	defer func() { require.NoError(t, os.Unsetenv("STEPLIB_BUILD_STATUS")) }()

	beforeWorkflow := models.WorkflowModel{
		BeforeRun: []string{"target"},
	}

	afterWorkflow := models.WorkflowModel{}

	workflow := models.WorkflowModel{
		BeforeRun: []string{"before"},
		AfterRun:  []string{"after"},
	}

	config := models.BitriseDataModel{
		FormatVersion:        "1.0.0",
		DefaultStepLibSource: "https://github.com/bitrise-io/bitrise-steplib.git",
		Workflows: map[string]models.WorkflowModel{
			"target": workflow,
			"before": beforeWorkflow,
			"after":  afterWorkflow,
		},
	}

	_, err := config.Validate()
	require.Error(t, err)

	require.Equal(t, "0", os.Getenv("BITRISE_BUILD_STATUS"))
	require.Equal(t, "0", os.Getenv("STEPLIB_BUILD_STATUS"))
}
Exemplo n.º 9
0
func TestToServiceConfigWhenUsingEnvVariables(t *testing.T) {
	ecsConfig := NewCliConfig(clusterName)
	ecsConfig.Region = region

	os.Setenv("AWS_ACCESS_KEY_ID", envAwsAccessKey)
	os.Setenv("AWS_SECRET_ACCESS_KEY", envAwsSecretKey)

	// Clear env variables as they persist past the individual test boundary
	defer func() {
		os.Unsetenv("AWS_ACCESS_KEY_ID")
		os.Unsetenv("AWS_SECRET_ACCESS_KEY")
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
	}()

	awsConfig, _ := ecsConfig.ToServiceConfig()
	resolvedCredentials, err := awsConfig.Credentials.Get()
	if err != nil {
		t.Error("Error fetching credentials from the chain provider")
	}

	if envAwsAccessKey != resolvedCredentials.AccessKeyID {
		t.Errorf("Invalid access key set. Expected [%s]. Got [%s]", envAwsAccessKey, resolvedCredentials.AccessKeyID)
	}
	if envAwsSecretKey != resolvedCredentials.SecretAccessKey {
		t.Errorf("Invalid secret key set. Expected [%s]. Got [%s]", envAwsSecretKey, resolvedCredentials.SecretAccessKey)
	}
}
Exemplo n.º 10
0
func init() {
	if runtime.GOOS == "darwin" {
		// remove DYLD_LIBRARY_PATH and LD_LIBRARY_PATH as they break VBoxManage on OSX
		os.Unsetenv("DYLD_LIBRARY_PATH")
		os.Unsetenv("LD_LIBRARY_PATH")
	}
}
Exemplo n.º 11
0
func TestEnvVarOverride(t *testing.T) {
	defer func() {
		loadedTemplates = make(map[string]*template.Template)
		os.Unsetenv(defaultTemplateDirectoryEnvVar)
	}()

	// first check that we fail with the wrong directory
	os.Setenv(defaultTemplateDirectoryEnvVar, filepath.Join("nosuchdir"))
	_, err := loadPageTemplate("error")
	if err == nil {
		t.Fatalf("Load with OS env directory %v", os.Getenv(defaultTemplateDirectoryEnvVar))
	}
	// now reset to the tests directory and try a test load
	os.Setenv(defaultTemplateDirectoryEnvVar, "tests")
	_, err = loadPageTemplate("test")
	if err != nil {
		t.Fatalf("Failed to load test template: %v", err)
	}
	// now unset the environment to use the default
	os.Unsetenv(defaultTemplateDirectoryEnvVar)
	_, err = loadPageTemplate("error")
	if err != nil {
		t.Fatalf("Failed to load error template: %v", err)
	}
}
Exemplo n.º 12
0
func TestEnv(t *testing.T) {

	os.Setenv("STR", "helloworld")
	os.Setenv("NUM", "42")
	os.Setenv("BOOL", "true")

	//config
	type Config struct {
		Str  string
		Num  int
		Bool bool
	}

	c := &Config{}

	//flag example parse
	if err := New(c).UseEnv().Process([]string{}); err != nil {
		t.Fatal(err)
	}

	os.Unsetenv("STR")
	os.Unsetenv("NUM")
	os.Unsetenv("BOOL")

	//check config is filled
	check(t, c.Str, `helloworld`)
	check(t, c.Num, 42)
	check(t, c.Bool, true)
}
Exemplo n.º 13
0
func TestEnvConvert(t *testing.T) {
	os.Setenv("TEST_PRUXY_1", "abc.com=127.0.0.1:8081,127.0.0.1:8082")
	os.Setenv("TEST_PRUXY_2", "abc.com/abc/123=127.0.0.1")
	defer os.Unsetenv("TEST_PRUXY_1")
	defer os.Unsetenv("TEST_PRUXY_2")

	p, _ := NewEnv("TEST_PRUXY_")
	convertFunc := p.DefaultRequestConverter()

	var convertTests = []struct {
		in  string
		out string
	}{
		{"http://abc.com/a/b/", "http://127.0.0.1:8081/a/b/"},
		{"http://abc.com/a/b", "http://127.0.0.1:8082/a/b"},
		{"http://abc.com/abc/123/456/hi", "http://127.0.0.1/456/hi"},
	}

	for i, tt := range convertTests {
		in, _ := http.NewRequest("GET", tt.in, nil)
		out := copyRequest(in)
		convertFunc(in, out)
		if out.URL.String() != tt.out {
			t.Errorf("%d expected %s, got %s", i, tt.out, out.URL.String())
		}
	}
}
Exemplo n.º 14
0
func (s *S) TestShellToContainerWithUnit(c *check.C) {
	transport := cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{
			Message: "",
			Status:  http.StatusOK,
		},
		CondFunc: func(req *http.Request) bool {
			return req.Method == "GET" && req.URL.Path == "/apps/myapp"
		},
	}
	guesser := cmdtest.FakeGuesser{Name: "myapp"}
	server := httptest.NewServer(buildHandler([]byte("hello my friend\nglad to see you here\n")))
	defer server.Close()
	target := "http://" + server.Listener.Addr().String()
	os.Setenv("TSURU_TARGET", target)
	defer os.Unsetenv("TSURU_TARGET")
	os.Setenv("TSURU_TOKEN", "abc123")
	defer os.Unsetenv("TSURU_TOKEN")
	var stdout, stderr, stdin bytes.Buffer
	context := Context{
		Args:   []string{"containerid"},
		Stdout: &stdout,
		Stderr: &stderr,
		Stdin:  &stdin,
	}
	var command ShellToContainerCmd
	command.GuessingCommand = GuessingCommand{G: &guesser}
	err := command.Flags().Parse(true, []string{"-a", "myapp"})
	c.Assert(err, check.IsNil)
	mngr := NewManager("admin", "0.1", "admin-ver", &stdout, &stderr, nil, nil)
	client := NewClient(&http.Client{Transport: &transport}, &context, mngr)
	err = command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(stdout.String(), check.Equals, "hello my friend\nglad to see you here\n")
}
Exemplo n.º 15
0
func (s *S) TestShellToContainerCmdConnectionRefused(c *check.C) {
	var buf bytes.Buffer
	transport := cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{
			Message: "",
			Status:  http.StatusOK,
		},
		CondFunc: func(req *http.Request) bool {
			return req.Method == "GET" && req.URL.Path == "/apps/cmd"
		},
	}
	server := httptest.NewServer(nil)
	addr := server.Listener.Addr().String()
	server.Close()
	os.Setenv("TSURU_TARGET", "http://"+addr)
	defer os.Unsetenv("TSURU_TARGET")
	os.Setenv("TSURU_TOKEN", "abc123")
	defer os.Unsetenv("TSURU_TOKEN")
	context := Context{
		Args:   []string{"af3332d"},
		Stdout: &buf,
		Stderr: &buf,
		Stdin:  &buf,
	}
	mngr := NewManager("admin", "0.1", "admin-ver", &buf, &buf, nil, nil)
	client := NewClient(&http.Client{Transport: &transport}, &context, mngr)
	var command ShellToContainerCmd
	err := command.Run(&context, client)
	c.Assert(err, check.NotNil)
}
Exemplo n.º 16
0
func teardown() {
	var dir string
	home := os.Getenv("PKIIO_HOME")
	if home != "" {
		dir = home
		os.Unsetenv("PKIIO_HOME")
	} else {
		local := os.Getenv("PKIIO_LOCAL")
		if local != "" {
			dir = local
			os.Unsetenv("PKIIO_LOCAL")
		} else {
			panic("No PKIIO env variables set")
		}
	}

	parentDir := path.Dir(dir)
	if strings.Contains(parentDir, "pki.io-test") {
		if err := os.RemoveAll(parentDir); err != nil {
			panic(err)
		}
	} else {
		panic("Directory isn't a pki.io test directory")
	}

}
Exemplo n.º 17
0
func TestClusterUpWithout2AvailabilityZones(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockECS := mock_ecs.NewMockECSClient(ctrl)
	mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)
	vpcAZs := "us-west-2c"

	os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
	os.Setenv("AWS_SECRET_KEY", "secret")
	defer func() {
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
	}()

	gomock.InOrder(
		mockCloudformation.EXPECT().Initialize(gomock.Any()),
		mockCloudformation.EXPECT().ValidateStackExists(stackName).Return(errors.New("error")),
	)
	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalSet.String("region", "us-west-1", "")
	globalContext := cli.NewContext(nil, globalSet, nil)

	flagSet := flag.NewFlagSet("ecs-cli-up", 0)
	flagSet.Bool(capabilityIAMFlag, true, "")
	flagSet.String(keypairNameFlag, "default", "")
	flagSet.Bool(forceFlag, true, "")
	flagSet.String(vpcAzFlag, vpcAZs, "")

	context := cli.NewContext(nil, flagSet, globalContext)
	err := createCluster(context, newMockReadWriter(), mockECS, mockCloudformation, ami.NewStaticAmiIds())
	if err == nil {
		t.Fatal("Expected error for 2 AZs")
	}
}
Exemplo n.º 18
0
func TestNewConfig(t *testing.T) {
	os.Setenv("AWS_ACCESS_KEY_ID", "access")
	os.Setenv("AWS_SECRET_ACCESS_KEY", "secret")
	c, err := NewConfig(false, 22375, false, true)
	if err != nil {
		t.Fatalf("Failed to create config. Error: %v", err)
	}
	if c.AWS.AccessKeyID != "access" {
		t.Error("AccessKeyID should be 'access': " + c.AWS.AccessKeyID)
	}
	if c.AWS.SecretAccessKey != "secret" {
		t.Error("SecretAccessKey should be 'secret': " + c.AWS.SecretAccessKey)
	}
	if c.Docker.Connection == "" {
		t.Error("config.Docker.Connection should not be empty.")
	}

	os.Unsetenv("AWS_ACCESS_KEY_ID")
	os.Unsetenv("AWS_ACCESS_KEY")
	os.Unsetenv("AWS_SECRET_ACCESS_KEY")
	os.Unsetenv("AWS_SECRET_KEY")

	c, err = NewConfig(false, 22375, false, true)
	if err == nil || err.Error() != "AWS_ACCESS_KEY_ID/AWS_ACCESS_KEY or AWS_SECRET_ACCESS_KEY/AWS_SECRET_KEY are missing." {
		t.Error("should return error when evn vars are not set")
	}

	c, err = NewConfig(true, 22375, false, false)
	if err != nil {
		t.Error("should not renturn an error")
	}
}
Exemplo n.º 19
0
func TestClusterUpWithClusterNameEmpty(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockECS := mock_ecs.NewMockECSClient(ctrl)
	mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)

	os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
	os.Setenv("AWS_SECRET_KEY", "secret")
	defer func() {
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
	}()

	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalSet.String("region", "us-west-1", "")
	globalContext := cli.NewContext(nil, globalSet, nil)

	flagSet := flag.NewFlagSet("ecs-cli-up", 0)
	flagSet.Bool(capabilityIAMFlag, true, "")
	flagSet.String(keypairNameFlag, "default", "")

	context := cli.NewContext(nil, flagSet, globalContext)
	err := createCluster(context, &mockReadWriter{clusterName: ""}, mockECS, mockCloudformation, ami.NewStaticAmiIds())
	if err == nil {
		t.Fatal("Expected error bringing up cluster")
	}
}
Exemplo n.º 20
0
func TestNewCliParamsWhenPrefixKeysAreNotPresent(t *testing.T) {
	os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
	os.Setenv("AWS_SECRET_KEY", "SECRET")
	defer func() {
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
	}()

	context := defaultConfig()

	// Prefixes are present, and values should be set to defaults
	rdwr := &mockReadWriter{isKeyPresentValue: false}
	params, err := NewCliParams(context, rdwr)
	if err != nil {
		t.Errorf("Unexpected error when getting new cli params", err)
	}

	if ecscli.ComposeProjectNamePrefixDefaultValue != params.ComposeProjectNamePrefix {
		t.Errorf("Compose project name prefix mismatch. Expected [%s] got [%s]", ecscli.ComposeProjectNamePrefixDefaultValue, params.ComposeProjectNamePrefix)
	}
	if ecscli.ComposeServiceNamePrefixDefaultValue != params.ComposeServiceNamePrefix {
		t.Errorf("Compose service name prefix mismatch. Expected [%s] got [%s]", ecscli.ComposeServiceNamePrefixDefaultValue, params.ComposeServiceNamePrefix)
	}
	if ecscli.CFNStackNamePrefixDefaultValue != params.CFNStackNamePrefix {
		t.Errorf("stack name name prefix mismatch. Expected [%s] got [%s]", ecscli.CFNStackNamePrefixDefaultValue, params.CFNStackNamePrefix)
	}

}
Exemplo n.º 21
0
func TestEnv(t *testing.T) {
	context := getContextOrFail(t)

	name := "ENV_TEST_NAME"
	testValue := "TEST_VALUE"
	os.Setenv(name, testValue)

	notExisting := "ENV_TEST_NOT_EXISTING"
	os.Unsetenv(notExisting)

	invalidName := "ENV_TEST_INVALID_NAME"
	os.Setenv("="+invalidName, testValue)

	env := context.Env()
	if value := env[name]; value != testValue {
		t.Errorf("Expected env-variable %s value '%s', found '%s'",
			name, testValue, value)
	}

	if value, ok := env[notExisting]; ok {
		t.Errorf("Expected empty env-variable %s, found '%s'",
			notExisting, value)
	}

	for k, v := range env {
		if strings.Contains(k, invalidName) {
			t.Errorf("Expected invalid name not to be included in Env %s, found in key '%s'", invalidName, k)
		}
		if strings.Contains(v, invalidName) {
			t.Errorf("Expected invalid name not be be included in Env %s, found in value '%s'", invalidName, v)
		}
	}

	os.Unsetenv("=" + invalidName)
}
Exemplo n.º 22
0
// The TestMain function creates a go command for testing purposes and
// deletes it after the tests have been run.
func TestMain(m *testing.M) {
	flag.Parse()

	if canRun {
		// We give the executable a .exe extension because Windows.
		out, err := exec.Command("go", "build", "-tags", "testgo", "-o", "testgo.exe").CombinedOutput()
		if err != nil {
			fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out)
			os.Exit(2)
		}
	}

	// Don't let these environment variables confuse the test.
	os.Unsetenv("GOBIN")
	os.Unsetenv("GOPATH")
	os.Unsetenv("GOROOT")

	r := m.Run()

	if canRun {
		os.Remove("testgo.exe")
	}

	os.Exit(r)
}
Exemplo n.º 23
0
func TestGetContainerURL(t *testing.T) {
	data := []struct {
		env  string
		url  string
		pass bool
	}{
		{"tcp://172.17.0.2:8000", "http://172.17.0.2:8000", true},
		{"", "", false},
		{"badlyformatted", "", false},
		{"tc", "", false},
	}

	defer os.Unsetenv(ENV_KEY)

	for _, tt := range data {
		if tt.env == "" {
			os.Unsetenv(ENV_KEY)
		} else {
			os.Setenv(ENV_KEY, tt.env)
		}

		url, err := getContainerURLFromEnv(CONTAINER_NAME, CONTAINER_PORT)
		if err == nil != tt.pass {
			if tt.pass {
				t.Errorf("Expected no errors but got %q: %+v", err.Error(), tt)
			} else {
				t.Errorf("Expected an error but got none (%s): %+v", url, tt)
			}
		}

		if tt.pass && url != tt.url {
			t.Errorf("Expected url %q but got %q", tt.url, url)
		}
	}
}
Exemplo n.º 24
0
func TestInitPaths(t *testing.T) {
	//
	// BITRISE_SOURCE_DIR

	// Unset BITRISE_SOURCE_DIR -> after InitPaths BITRISE_SOURCE_DIR should be CurrentDir
	if os.Getenv(BitriseSourceDirEnvKey) != "" {
		require.Equal(t, nil, os.Unsetenv(BitriseSourceDirEnvKey))
	}
	require.Equal(t, nil, InitPaths())
	require.Equal(t, CurrentDir, os.Getenv(BitriseSourceDirEnvKey))

	// Set BITRISE_SOURCE_DIR -> after InitPaths BITRISE_SOURCE_DIR should keep content
	require.Equal(t, nil, os.Setenv(BitriseSourceDirEnvKey, "$HOME/test"))
	require.Equal(t, nil, InitPaths())
	require.Equal(t, "$HOME/test", os.Getenv(BitriseSourceDirEnvKey))

	//
	// BITRISE_DEPLOY_DIR

	// Unset BITRISE_DEPLOY_DIR -> after InitPaths BITRISE_DEPLOY_DIR should be temp dir
	if os.Getenv(BitriseDeployDirEnvKey) != "" {
		require.Equal(t, nil, os.Unsetenv(BitriseDeployDirEnvKey))
	}
	require.Equal(t, nil, InitPaths())
	require.NotEqual(t, "", os.Getenv(BitriseDeployDirEnvKey))

	// Set BITRISE_DEPLOY_DIR -> after InitPaths BITRISE_DEPLOY_DIR should keep content
	require.Equal(t, nil, os.Setenv(BitriseDeployDirEnvKey, "$HOME/test"))
	require.Equal(t, nil, InitPaths())
	require.Equal(t, "$HOME/test", os.Getenv(BitriseDeployDirEnvKey))
}
Exemplo n.º 25
0
func (s *RunSuite) TestInterpolationWithExtends(c *C) {
	os.Setenv("IMAGE", "tianon/true")
	os.Setenv("TEST_PORT", "8000")

	p := s.CreateProjectFromText(c, `
        test:
                extends:
                        file: ./assets/interpolation/docker-compose.yml
                        service: base
                ports:
                        - ${TEST_PORT}
        `)

	name := fmt.Sprintf("%s_%s_1", p, "test")
	testContainer := s.GetContainerByName(c, name)

	p = s.CreateProjectFromText(c, `
	reference:
	  image: tianon/true
		ports:
		  - 8000
	`)

	name = fmt.Sprintf("%s_%s_1", p, "reference")
	referenceContainer := s.GetContainerByName(c, name)

	c.Assert(testContainer, NotNil)

	c.Assert(referenceContainer.Image, Equals, testContainer.Image)

	os.Unsetenv("TEST_PORT")
	os.Unsetenv("IMAGE")
}
Exemplo n.º 26
0
func TestEnv(t *testing.T) {

	os.Setenv("STR", "helloworld")
	os.Setenv("NUM", "42")
	os.Setenv("BOOL", "true")

	//config
	type Config struct {
		Str  string
		Num  int
		Bool bool
	}

	c := &Config{}

	//flag example parse
	New(c).UseEnv().Parse()

	os.Unsetenv("STR")
	os.Unsetenv("NUM")
	os.Unsetenv("BOOL")

	//check config is filled
	check(t, c.Str, `helloworld`)
	check(t, c.Num, 42)
	check(t, c.Bool, true)
}
Exemplo n.º 27
0
func UnsetFixtures() {
	for key, _ := range Fixtures {
		os.Unsetenv(key)
	}

	// and others, sometimes
	os.Unsetenv("F_BLANK")
	os.Unsetenv("F_WHITESPACE")
}
Exemplo n.º 28
0
func TestSdWatchdogEnabled(t *testing.T) {
	mypid := strconv.Itoa(os.Getpid())
	tests := []struct {
		usec     string // empty => unset
		pid      string // empty => unset
		unsetEnv bool   // arbitrarily set across testcases

		werr   bool
		wdelay time.Duration
	}{
		// Success cases
		{"100", mypid, true, false, 100 * time.Microsecond},
		{"50", mypid, true, false, 50 * time.Microsecond},
		{"1", mypid, false, false, 1 * time.Microsecond},
		{"1", "", true, false, 1 * time.Microsecond},

		// No-op cases
		{"", mypid, true, false, 0}, // WATCHDOG_USEC not set
		{"1", "0", false, false, 0}, // WATCHDOG_PID doesn't match
		{"", "", true, false, 0},    // Both not set

		// Failure cases
		{"-1", mypid, true, true, 0},                // Negative USEC
		{"string", "1", false, true, 0},             // Non-integer USEC value
		{"1", "string", true, true, 0},              // Non-integer PID value
		{"stringa", "stringb", false, true, 0},      // E v e r y t h i n g
		{"-10239", "-eleventythree", true, true, 0}, // i s   w r o n g
	}

	for i, tt := range tests {
		if tt.usec != "" {
			must(os.Setenv("WATCHDOG_USEC", tt.usec))
		} else {
			must(os.Unsetenv("WATCHDOG_USEC"))
		}
		if tt.pid != "" {
			must(os.Setenv("WATCHDOG_PID", tt.pid))
		} else {
			must(os.Unsetenv("WATCHDOG_PID"))
		}

		delay, err := SdWatchdogEnabled(tt.unsetEnv)

		if tt.werr && err == nil {
			t.Errorf("#%d: want non-nil err, got nil", i)
		} else if !tt.werr && err != nil {
			t.Errorf("#%d: want nil err, got %v", i, err)
		}
		if tt.wdelay != delay {
			t.Errorf("#%d: want delay=%d, got %d", i, tt.wdelay, delay)
		}
		if tt.unsetEnv && (os.Getenv("WATCHDOG_PID") != "" || os.Getenv("WATCHDOG_USEC") != "") {
			t.Errorf("#%d: environment variables not cleaned up", i)
		}
	}
}
Exemplo n.º 29
0
func TestClusterUpForImageIdInput(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockEcs := mock_ecs.NewMockECSClient(ctrl)
	mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)
	imageId := "ami-12345"

	os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
	os.Setenv("AWS_SECRET_KEY", "secret")
	defer func() {
		os.Unsetenv("AWS_ACCESS_KEY")
		os.Unsetenv("AWS_SECRET_KEY")
	}()

	gomock.InOrder(
		mockEcs.EXPECT().Initialize(gomock.Any()),
		mockEcs.EXPECT().CreateCluster(gomock.Any()).Do(func(in interface{}) {
			if in.(string) != clusterName {
				t.Fatal("Expected to be called with " + clusterName + " not " + in.(string))
			}
		}).Return(clusterName, nil),
	)

	gomock.InOrder(
		mockCloudformation.EXPECT().Initialize(gomock.Any()),
		mockCloudformation.EXPECT().ValidateStackExists(gomock.Any()).Return(errors.New("error")),
		mockCloudformation.EXPECT().CreateStack(gomock.Any(), gomock.Any(), gomock.Any()).Do(func(x, y, z interface{}) {
			cfnStackParams := z.(*cloudformation.CfnStackParams)
			param, err := cfnStackParams.GetParameter(cloudformation.ParameterKeyAmiId)
			if err != nil {
				t.Fatal("Expected image id params to be present")
			}
			if imageId != aws.StringValue(param.ParameterValue) {
				t.Fatalf("Expected image id to equal %s but got %s", imageId, aws.StringValue(param.ParameterValue))
			}
		}).Return("", nil),
		mockCloudformation.EXPECT().WaitUntilCreateComplete(gomock.Any()).Return(nil),
	)

	globalSet := flag.NewFlagSet("ecs-cli", 0)
	globalSet.String("region", "us-west-1", "")
	globalContext := cli.NewContext(nil, globalSet, nil)

	flagSet := flag.NewFlagSet("ecs-cli-up", 0)
	flagSet.Bool(capabilityIAMFlag, true, "")
	flagSet.String(keypairNameFlag, "default", "")
	flagSet.String(imageIdFlag, imageId, "")
	flagSet.String(certificateFlag, "default", "")

	context := cli.NewContext(nil, flagSet, globalContext)
	err := createCluster(context, &mockReadWriter{}, mockEcs, mockCloudformation, ami.NewStaticAmiIds())
	if err != nil {
		t.Fatal("Error bringing up cluster: ", err)
	}
}
Exemplo n.º 30
0
func TestPbftF0(t *testing.T) {
	net := makeTestnet(1, func(inst *instance) {
		os.Setenv("OPENCHAIN_OBCPBFT_GENERAL_N", fmt.Sprintf("%d", inst.net.N)) // TODO, a little hacky, but needed for state transfer not to get upset
		os.Setenv("OPENCHAIN_OBCPBFT_GENERAL_F", "0")                           // TODO, a little hacky, but needed for state transfer not to get upset
		defer func() {
			os.Unsetenv("OPENCHAIN_OBCPBFT_GENERAL_N")
			os.Unsetenv("OPENCHAIN_OBCPBFT_GENERAL_F")
		}()
		config := loadConfig()
		inst.pbft = newPbftCore(uint64(inst.id), config, inst, inst)
		inst.pbft.replicaCount = inst.net.N
		inst.pbft.f = inst.net.f
		inst.deliver = func(msg []byte, senderHandle *pb.PeerID) {
			senderID, _ := getValidatorID(senderHandle)
			inst.pbft.receive(msg, senderID)
		}

	})
	defer net.close()

	// Create a message of type: `OpenchainMessage_CHAIN_TRANSACTION`
	txTime := &gp.Timestamp{Seconds: 1, Nanos: 0}
	tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_NEW, Timestamp: txTime, Payload: []byte("TestNetwork")}
	txPacked, err := proto.Marshal(tx)
	if err != nil {
		t.Fatalf("Failed to marshal TX block: %s", err)
	}
	err = net.replicas[0].pbft.request(txPacked, 0)
	if err != nil {
		t.Fatalf("Request failed: %s", err)
	}

	err = net.process()
	if err != nil {
		t.Fatalf("Processing failed: %s", err)
	}

	for _, inst := range net.replicas {
		blockHeight, _ := inst.ledger.GetBlockchainSize()
		if blockHeight <= 1 {
			t.Errorf("Instance %d did not execute transaction", inst.id)
			continue
		}
		if blockHeight != 2 {
			t.Errorf("Instance %d executed more than one transaction", inst.id)
			continue
		}
		highestBlock, _ := inst.ledger.GetBlock(blockHeight - 1)
		if !reflect.DeepEqual(highestBlock.Transactions[0].Payload, txPacked) {
			t.Errorf("Instance %d executed wrong transaction, %x should be %x",
				inst.id, highestBlock.Transactions[0].Payload, txPacked)
		}
	}
}