Exemplo n.º 1
0
func main() {
	fmt.Println("starting drone-cowpoke...")

	workspace := plugin.Workspace{}
	vargs := Cowpoke{}

	plugin.Param("workspace", &workspace)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()

	if len(vargs.Url) == 0 {
		fmt.Println("no cowpoke url was specified")
		os.Exit(1)
	}

	if vargs.Port == 0 {
		fmt.Println("no cowpoke port was specified")
		os.Exit(1)
	}

	fmt.Println("loading image data from", filepath.Join(workspace.Path, ".docker.json"))
	image := GetImageName(filepath.Join(workspace.Path, ".docker.json"))

	if len(image) <= 0 {
		fmt.Println("image load failed from .docker.json")
		os.Exit(1)
	}

	var cowpokeUrl = fmt.Sprintf("%s:%d/api/environment/", vargs.Url, vargs.Port)
	fmt.Println("cowpoke url set to:", cowpokeUrl)
	fmt.Println(".docker.json value being posted:", image)
	ExecutePut(cowpokeUrl + url.QueryEscape(image))

	fmt.Println("finished drone-cowpoke.")
}
Exemplo n.º 2
0
func main() {
	log.SetFlags(0)
	plugin.Param("workspace", &workspace)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()

	script := strings.Join(vargs.Script, "\n")
	if err := ioutil.WriteFile(scriptName, []byte(script), 0644); err != nil {
		log.Fatalf("WriteFile(%q): %v", script, err)
	}

	c := vargs.Cmd
	if c == "" {
		c = defaultCmd
	}
	cmd := exec.Command(c, scriptName)
	cmd.Dir = workspace.Path
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Env = append(os.Environ(), vargs.Env...)

	fmt.Println("$", strings.Join(cmd.Args, " "))
	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}
}
Exemplo n.º 3
0
func main() {
	log.SetFlags(0)
	plugin.Param("workspace", &workspace)
	plugin.Param("build", &build)
	plugin.Param("repo", &repo)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()
	sort.Strings(vargs.Gzip) // need for matchGzip

	// context for all clients
	ctx := context.Background()
	// GitHub client
	gts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: vargs.GitHubToken})
	client.ghub = github.NewClient(oauth2.NewClient(ctx, gts))
	// GCS client
	auth, err := google.JWTConfigFromJSON([]byte(vargs.AuthKey), storage.ScopeFullControl)
	if err != nil {
		fatalf("auth: %v", err)
	}
	tsrc := auth.TokenSource(ctx)
	client.gcs, err = storage.NewClient(ctx, cloud.WithTokenSource(auth.TokenSource(ctx)))
	if err != nil {
		fatalf("storage client: %v", err)
	}
	// http client with service account authorization
	client.http = oauth2.NewClient(ctx, tsrc)

	run()
	if ecode != 0 {
		msg := fmt.Sprintf("exited with code %d", ecode)
		updateStatus("error", msg, stagingURL)
	}
	os.Exit(ecode)
}
Exemplo n.º 4
0
func main() {
	fmt.Printf("Drone Terraform Plugin built from %s\n", buildCommit)

	workspace := plugin.Workspace{}
	vargs := terraform{}

	plugin.Param("workspace", &workspace)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()

	if vargs.RoleARN != "" {
		assumeRole(vargs.RoleARN)
	}

	var commands []*exec.Cmd
	remote := vargs.Remote
	if vargs.Cacert != "" {
		commands = append(commands, installCaCert(vargs.Cacert))
	}
	if remote.Backend != "" {
		commands = append(commands, deleteCache())
		commands = append(commands, remoteConfigCommand(remote))
	}
	commands = append(commands, getModules())
	commands = append(commands, planCommand(vargs.Vars, vargs.Parallelism))
	if !vargs.Plan {
		commands = append(commands, applyCommand(vargs.Parallelism))
	}
	commands = append(commands, deleteCache())

	for _, c := range commands {
		c.Env = os.Environ()
		c.Dir = workspace.Path
		if c.Dir == "" {
			wd, err := os.Getwd()
			if err == nil {
				c.Dir = wd
			}
		}
		if vargs.RootDir != "" {
			c.Dir = c.Dir + "/" + vargs.RootDir
		}
		c.Stdout = os.Stdout
		c.Stderr = os.Stderr
		if !vargs.Sensitive {
			trace(c)
		}

		err := c.Run()
		if err != nil {
			fmt.Println("Error!")
			fmt.Println(err)
			os.Exit(1)
		}
		fmt.Println("Command completed successfully")
	}

}
Exemplo n.º 5
0
func main() {
	workspace := plugin.Workspace{}
	vargs := S3{}

	plugin.Param("workspace", &workspace)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()

	// skip if AWS key or SECRET are empty. A good example for this would
	// be forks building a project. S3 might be configured in the source
	// repo, but not in the fork
	if len(vargs.Key) == 0 || len(vargs.Secret) == 0 {
		return
	}

	// make sure a default region is set
	if len(vargs.Region) == 0 {
		vargs.Region = "us-east-1"
	}

	// make sure a default access is set
	// let's be conservative and assume private
	if len(vargs.Access) == 0 {
		vargs.Access = "private"
	}

	// if the target starts with a "/" we need
	// to remove it, otherwise we might adding
	// a 3rd slash to s3://
	if strings.HasPrefix(vargs.Target, "/") {
		vargs.Target = vargs.Target[1:]
	}

	cmd := command(vargs)
	cmd.Env = os.Environ()
	if len(vargs.Key) > 0 {
		cmd.Env = append(cmd.Env, "AWS_ACCESS_KEY_ID="+vargs.Key)
	}
	if len(vargs.Secret) > 0 {
		cmd.Env = append(cmd.Env, "AWS_SECRET_ACCESS_KEY="+vargs.Secret)
	}
	cmd.Dir = workspace.Path
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	trace(cmd)

	// run the command and exit if failed.
	err := cmd.Run()
	if err != nil {
		os.Exit(1)
	}
}
Exemplo n.º 6
0
func main() {
	v := new(Params)
	r := new(plugin.Repo)
	b := new(plugin.Build)
	w := new(plugin.Workspace)
	plugin.Param("repo", r)
	plugin.Param("build", b)
	plugin.Param("workspace", w)
	plugin.Param("vargs", &v)
	plugin.MustParse()

	err := clone(r, b, w, v)
	if err != nil {
		os.Exit(1)
	}
}
Exemplo n.º 7
0
func main() {
	fmt.Printf("Drone Mercurial Plugin built at %s\n", buildDate)

	v := new(Params)
	r := new(plugin.Repo)
	b := new(plugin.Build)
	w := new(plugin.Workspace)
	plugin.Param("repo", r)
	plugin.Param("build", b)
	plugin.Param("workspace", w)
	plugin.Param("vargs", &v)
	plugin.MustParse()

	err := run(r, b, w, v)
	if err != nil {
		os.Exit(1)
	}
}
Exemplo n.º 8
0
func main() {
	log.SetFlags(0)
	plugin.Param("workspace", &workspace)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()
	sort.Strings(vargs.Gzip) // need for matchGzip

	auth, err := google.JWTConfigFromJSON([]byte(vargs.AuthKey), storage.ScopeFullControl)
	if err != nil {
		fatalf("auth: %v", err)
	}
	ctx := context.Background()
	client, err := storage.NewClient(ctx, cloud.WithTokenSource(auth.TokenSource(ctx)))
	if err != nil {
		fatalf("storage client: %v", err)
	}
	run(client)
	os.Exit(ecode)
}
Exemplo n.º 9
0
func main() {
	testExpressions()
	workspace := plugin.Workspace{}
	repo := plugin.Repo{}
	build := plugin.Build{}
	vargs := mavendeploy.Maven{}

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

	vargs.WorkspacePath(workspace.Path)

	err := vargs.Publish()
	if err != nil {
		panic(err)
	}
}
Exemplo n.º 10
0
func main() {
	workspace := plugin.Workspace{}
	build := plugin.Build{}
	vargs := Ansible{}

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

	vargs = setDefaults(vargs)

	// write the rsa private key
	if err := writeKey(workspace); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// write ansible configuration
	if err := writeAnsibleConf(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// Run ansible
	cmd := command(vargs, workspace)
	trace(cmd)

	cmd.Env = os.Environ()
	cmd.Dir = workspace.Path
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err := cmd.Run()
	if err != nil {
		fmt.Printf("Failed to deploy playbook %s with inventory %s: %s", vargs.Playbook, vargs.Inventory, err)
		os.Exit(1)
	}
}
Exemplo n.º 11
0
func main() {
	fmt.Printf("Drone Google Cloud Storage Plugin built from %s\n", buildCommit)

	log.SetFlags(0)
	plugin.Param("workspace", &workspace)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()
	sort.Strings(vargs.Gzip) // need for matchGzip
	rand.Seed(time.Now().UnixNano())

	auth, err := google.JWTConfigFromJSON([]byte(vargs.AuthKey), storage.ScopeFullControl)
	if err != nil {
		fatalf("auth: %v", err)
	}
	ctx := context.Background()
	client, err := storage.NewClient(ctx, cloud.WithTokenSource(auth.TokenSource(ctx)))
	if err != nil {
		fatalf("storage client: %v", err)
	}
	run(client)
	os.Exit(ecode)
}
Exemplo n.º 12
0
func main() {
	d := new(deployer)
	w := new(plugin.Workspace)

	plugin.Param("vargs", d)
	plugin.Param("workspace", w)
	plugin.MustParse()

	// Save ssh keys
	if err := os.MkdirAll("/root/.ssh", 0700); err != nil {
		log.Fatal(err)
	}

	if err := ioutil.WriteFile("/root/.ssh/config", []byte(SSHConfig), 0644); err != nil {
		log.Fatal(err)
	}

	if err := ioutil.WriteFile("/root/.ssh/id_rsa", []byte(w.Keys.Private), 0600); err != nil {
		log.Fatal(err)
	}

	if err := ioutil.WriteFile("/root/.ssh/id_rsa.pub", []byte(w.Keys.Public), 0644); err != nil {
		log.Fatal(err)
	}

	c := exec.Command("/bin/dep", "-n", d.Task, d.Stage)
	c.Dir = w.Path
	c.Stdout = os.Stdout
	c.Stderr = os.Stderr

	err := c.Run()
	if err != nil {
		log.Fatal(err)
	}

	log.Println("Command completed successfully")
}
Exemplo n.º 13
0
func main() {

	workspace := plugin.Workspace{}
	vargs := terraform{}

	plugin.Param("workspace", &workspace)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()

	var commands []*exec.Cmd
	remote := vargs.Remote
	if remote.Backend != "" {
		commands = append(commands, remoteConfigCommand(remote))
	}
	commands = append(commands, planCommand(vargs.Vars))
	if !vargs.DryRun {
		commands = append(commands, applyCommand())
	}

	for _, c := range commands {
		c.Env = os.Environ()
		c.Dir = workspace.Path
		c.Stdout = os.Stdout
		c.Stderr = os.Stderr
		trace(c)

		err := c.Run()
		if err != nil {
			fmt.Println("Error!")
			fmt.Println(err)
			os.Exit(1)
		}
		fmt.Println("Command completed successfully")
	}

}
Exemplo n.º 14
0
func main() {
	workspace := plugin.Workspace{}
	build := plugin.Build{}
	vargs := Docker{}

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

	// in case someone uses the shorthand repository name
	// with a custom registry, we should concatinate so that
	// we have the fully qualified image name.
	if strings.Count(vargs.Repo, "/") == 1 && len(vargs.Registry) != 0 {
		vargs.Repo = fmt.Sprintf("%s/%s", vargs.Registry, vargs.Repo)
	}

	// Set the Registry value
	if len(vargs.Registry) == 0 {
		vargs.Registry = "https://index.docker.io/v1/"
	}
	// Set the Dockerfile path
	if len(vargs.File) == 0 {
		vargs.File = "."
	}
	// Set the Tag value
	if len(vargs.Tag) == 0 {
		vargs.Tag = "latest"
	}
	vargs.Repo = fmt.Sprintf("%s:%s", vargs.Repo, vargs.Tag)

	go func() {
		args := []string{"-d"}

		if len(vargs.Storage) != 0 {
			args = append(args, "-s", vargs.Storage)
		}
		if vargs.Insecure && len(vargs.Registry) != 0 {
			args = append(args, "--insecure-registry", vargs.Registry)
		}

		for _, value := range vargs.Dns {
			args = append(args, "--dns", value)
		}

		cmd := exec.Command("/usr/bin/docker", args...)
		if os.Getenv("DOCKER_LAUNCH_DEBUG") == "true" {
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
		} else {
			cmd.Stdout = ioutil.Discard
			cmd.Stderr = ioutil.Discard
		}
		trace(cmd)
		cmd.Run()
	}()

	// ping Docker until available
	for i := 0; i < 3; i++ {
		cmd := exec.Command("/usr/bin/docker", "info")
		cmd.Stdout = ioutil.Discard
		cmd.Stderr = ioutil.Discard
		err := cmd.Run()
		if err == nil {
			break
		}
		time.Sleep(time.Second * 5)
	}

	// Login to Docker
	if len(vargs.Username) != 0 {
		cmd := exec.Command("/usr/bin/docker", "login", "-u", vargs.Username, "-p", vargs.Password, "-e", vargs.Email, vargs.Registry)
		cmd.Dir = workspace.Path
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		err := cmd.Run()
		if err != nil {
			fmt.Println("Login failed.")
			os.Exit(1)
		}
	} else {
		fmt.Printf("A username was not specified. Assuming anoynmous publishing.\n")
	}

	// Docker environment info
	cmd := exec.Command("/usr/bin/docker", "version")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	trace(cmd)
	cmd.Run()
	cmd = exec.Command("/usr/bin/docker", "info")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	trace(cmd)
	cmd.Run()

	// Build the container
	cmd = exec.Command("/usr/bin/docker", "build", "--pull=true", "--rm=true", "-t", vargs.Repo, vargs.File)
	cmd.Dir = workspace.Path
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	trace(cmd)
	err := cmd.Run()
	if err != nil {
		os.Exit(1)
	}

	// Push the container
	cmd = exec.Command("/usr/bin/docker", "push", vargs.Repo)
	cmd.Dir = workspace.Path
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	trace(cmd)
	err = cmd.Run()
	if err != nil {
		os.Exit(1)
	}
}
Exemplo n.º 15
0
func main() {
	workspace := plugin.Workspace{}
	build := plugin.Build{}
	vargs := Docker{}

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

	// in case someone uses the shorthand repository name
	// with a custom registry, we should concatinate so that
	// we have the fully qualified image name.
	if strings.Count(vargs.Repo, "/") <= 1 && len(vargs.Registry) != 0 && !strings.HasPrefix(vargs.Repo, vargs.Registry) {
		vargs.Repo = fmt.Sprintf("%s/%s", vargs.Registry, vargs.Repo)
	}

	// Set the Registry value
	if len(vargs.Registry) == 0 {
		vargs.Registry = "https://index.docker.io/v1/"
	}
	// Set the Dockerfile name
	if len(vargs.File) == 0 {
		vargs.File = "Dockerfile"
	}
	// Set the Context value
	if len(vargs.Context) == 0 {
		vargs.Context = "."
	}
	// Set the Tag value
	if vargs.Tag.Len() == 0 {
		vargs.Tag = StrSlice{[]string{"latest"}}
	}
	// Get absolute path for 'save' file
	if len(vargs.Save.File) != 0 {
		if !filepath.IsAbs(vargs.Save.File) {
			vargs.Save.File = filepath.Join(workspace.Path, vargs.Save.File)
		}
	}
	// Get absolute path for 'load' file
	if len(vargs.Load) != 0 {
		if !filepath.IsAbs(vargs.Load) {
			vargs.Load = filepath.Join(workspace.Path, vargs.Load)
		}
	}

	go func() {
		args := []string{"-d"}

		if len(vargs.Storage) != 0 {
			args = append(args, "-s", vargs.Storage)
		}
		if vargs.Insecure && len(vargs.Registry) != 0 {
			args = append(args, "--insecure-registry", vargs.Registry)
		}
		if len(vargs.Mirror) != 0 {
			args = append(args, "--registry-mirror", vargs.Mirror)
		}

		for _, value := range vargs.Dns {
			args = append(args, "--dns", value)
		}

		cmd := exec.Command("/usr/bin/docker", args...)
		if os.Getenv("DOCKER_LAUNCH_DEBUG") == "true" {
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
		} else {
			cmd.Stdout = ioutil.Discard
			cmd.Stderr = ioutil.Discard
		}
		trace(cmd)
		cmd.Run()
	}()

	// ping Docker until available
	for i := 0; i < 3; i++ {
		cmd := exec.Command("/usr/bin/docker", "info")
		cmd.Stdout = ioutil.Discard
		cmd.Stderr = ioutil.Discard
		err := cmd.Run()
		if err == nil {
			break
		}
		time.Sleep(time.Second * 5)
	}

	// Login to Docker
	if len(vargs.Username) != 0 {
		cmd := exec.Command("/usr/bin/docker", "login", "-u", vargs.Username, "-p", vargs.Password, "-e", vargs.Email, vargs.Registry)
		cmd.Dir = workspace.Path
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		err := cmd.Run()
		if err != nil {
			fmt.Println("Login failed.")
			os.Exit(1)
		}
	} else {
		fmt.Printf("A username was not specified. Assuming anoynmous publishing.\n")
	}

	// Docker environment info
	cmd := exec.Command("/usr/bin/docker", "version")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	trace(cmd)
	cmd.Run()
	cmd = exec.Command("/usr/bin/docker", "info")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	trace(cmd)
	cmd.Run()

	// Restore from tarred image repository
	if len(vargs.Load) != 0 {
		if _, err := os.Stat(vargs.Load); err != nil {
			fmt.Printf("Archive %s does not exist. Building from scratch.\n", vargs.Load)
		} else {
			cmd := exec.Command("/usr/bin/docker", "load", "-i", vargs.Load)
			cmd.Dir = workspace.Path
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			trace(cmd)
			err := cmd.Run()
			if err != nil {
				os.Exit(1)
			}
		}
	}

	// Build the container
	name := fmt.Sprintf("%s:%s", vargs.Repo, vargs.Tag.Slice()[0])
	cmd = exec.Command("/usr/bin/docker", "build", "--pull=true", "--rm=true", "-f", vargs.File, "-t", name, vargs.Context)
	cmd.Dir = workspace.Path
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	trace(cmd)
	err := cmd.Run()
	if err != nil {
		os.Exit(1)
	}

	// Creates image tags
	for _, tag := range vargs.Tag.Slice()[1:] {
		name_ := fmt.Sprintf("%s:%s", vargs.Repo, tag)
		cmd = exec.Command("/usr/bin/docker", "tag", name, name_)
		cmd.Dir = workspace.Path
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		trace(cmd)
		err = cmd.Run()
		if err != nil {
			os.Exit(1)
		}
	}

	// Push the image and tags to the registry
	for _, tag := range vargs.Tag.Slice() {
		name_ := fmt.Sprintf("%s:%s", vargs.Repo, tag)
		cmd = exec.Command("/usr/bin/docker", "push", name_)
		cmd.Dir = workspace.Path
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		trace(cmd)
		err = cmd.Run()
		if err != nil {
			os.Exit(1)
		}
	}

	// Save to tarred image repository
	if len(vargs.Save.File) != 0 {
		// if the destination directory does not exist, create it
		dir := filepath.Dir(vargs.Save.File)
		os.MkdirAll(dir, 0755)

		cmd = exec.Command("/usr/bin/docker", "save", "-o", vargs.Save.File)

		// Limit saving to the given tags
		if vargs.Save.Tags.Len() != 0 {
			for _, tag := range vargs.Save.Tags.Slice() {
				name_ := fmt.Sprintf("%s:%s", vargs.Repo, tag)
				cmd.Args = append(cmd.Args, name_)
			}
		} else {
			cmd.Args = append(cmd.Args, vargs.Repo)
		}

		cmd.Dir = workspace.Path
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		trace(cmd)
		err := cmd.Run()
		if err != nil {
			os.Exit(1)
		}
	}
}
Exemplo n.º 16
0
func main() {
	workspace := plugin.Workspace{}
	build := plugin.Build{}
	vargs := Docker{}

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

	// Repository name should have gcr prefix
	if len(vargs.Registry) == 0 {
		vargs.Registry = "gcr.io"
	}
	// Set the Dockerfile name
	if len(vargs.File) == 0 {
		vargs.File = "Dockerfile"
	}
	// Set the Context value
	if len(vargs.Context) == 0 {
		vargs.Context = "."
	}
	// Set the Tag value
	if vargs.Tag.Len() == 0 {
		vargs.Tag = StrSlice{[]string{"latest"}}
	}
	// Concat the Registry URL and the Repository name if necessary
	if strings.Count(vargs.Repo, "/") == 1 {
		vargs.Repo = fmt.Sprintf("%s/%s", vargs.Registry, vargs.Repo)
	}
	// Trim any spaces or newlines from the token
	vargs.Token = strings.TrimSpace(vargs.Token)

	go func() {
		args := []string{"-d"}

		if len(vargs.Storage) != 0 {
			args = append(args, "-s", vargs.Storage)
		}

		cmd := exec.Command("/usr/bin/docker", args...)
		if os.Getenv("DOCKER_LAUNCH_DEBUG") == "true" {
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
		} else {
			cmd.Stdout = ioutil.Discard
			cmd.Stderr = ioutil.Discard
		}
		trace(cmd)
		cmd.Run()
	}()

	// ping Docker until available
	for i := 0; i < 3; i++ {
		cmd := exec.Command("/usr/bin/docker", "info")
		cmd.Stdout = ioutil.Discard
		cmd.Stderr = ioutil.Discard
		err := cmd.Run()
		if err == nil {
			break
		}
		time.Sleep(time.Second * 5)
	}

	// Login to Docker
	cmd := exec.Command("/usr/bin/docker", "login", "-u", "_json_key", "-p", vargs.Token, "-e", "*****@*****.**", vargs.Registry)
	cmd.Dir = workspace.Path
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		fmt.Println("Login failed.")
		os.Exit(1)
	}

	// Build the container
	cmd = exec.Command("/usr/bin/docker", "build", "--pull=true", "--rm=true", "-f", vargs.File, "-t", build.Commit, vargs.Context)
	cmd.Dir = workspace.Path
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	trace(cmd)
	err = cmd.Run()
	if err != nil {
		os.Exit(1)
	}

	// Creates image tags
	for _, tag := range vargs.Tag.Slice() {
		// create the full tag name
		tag_ := fmt.Sprintf("%s:%s", vargs.Repo, tag)
		if tag == "latest" {
			tag_ = vargs.Repo
		}

		// tag the build image sha
		cmd = exec.Command("/usr/bin/docker", "tag", build.Commit, tag_)
		cmd.Dir = workspace.Path
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		trace(cmd)
		err = cmd.Run()
		if err != nil {
			os.Exit(1)
		}
	}

	// Push the image and tags to the registry
	cmd = exec.Command("/usr/bin/docker", "push", vargs.Repo)
	cmd.Dir = workspace.Path
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	trace(cmd)
	err = cmd.Run()
	if err != nil {
		os.Exit(1)
	}
}
Exemplo n.º 17
0
func main() {
	fmt.Println("starting drone-rancher-catalog...")

	var catalog = catalog{}
	plugin.Param("workspace", &catalog.workspace)
	plugin.Param("repo", &catalog.repo)
	plugin.Param("build", &catalog.build)
	plugin.Param("vargs", &catalog.vargs)
	plugin.MustParse()

	check(catalog.vargs.DockerRepo, "ERROR: docker_repo: Docker Registry Repo to read tags from, not specified")
	check(catalog.vargs.DockerUsername, "ERROR: docker_username: Docker Registry Username not specified")
	check(catalog.vargs.DockerPassword, "ERROR: docker_password: Docker Registry Password not specified")
	check(catalog.vargs.CatalogRepo, "ERROR: catalog_repo: GitHub Catalog Repo not specified")
	check(catalog.vargs.GitHubToken, "ERROR: github_token: GitHub User Token not specified")
	check(catalog.vargs.CowpokeURL, "ERROR: cowpoke_url: cowpoke url not specified")
	check(catalog.vargs.RancherCatalogName, "ERROR: rancher_catalog_name: catalog name in rancher is not specified")

	if len(catalog.vargs.DockerURL) == 0 {
		catalog.vargs.DockerURL = "https://registry.hub.docker.com/"
	}
	if len(catalog.vargs.GitHubUser) == 0 {
		catalog.vargs.GitHubUser = catalog.build.Author
	}
	if len(catalog.vargs.GitHubEmail) == 0 {
		catalog.vargs.GitHubEmail = catalog.build.Email
	}

	// create a dir outside the workspace
	if !exists(baseDir) {
		os.Mkdir(baseDir, 0755)
	}

	catalog.cloneCatalogRepo()
	os.Chdir(repoDir)
	catalog.gitConfigureEmail()
	catalog.gitConfigureUser()

	if !exists("./templates") {
		os.Mkdir("./templates", 0755)
	}

	dockerComposeTmpl := catalog.parseTemplateFile(dockerComposeTemplateFile)
	rancherComposeTmpl := catalog.parseTemplateFile(rancherComposeTemplateFile)
	configTmpl := catalog.parseTemplateFile(configTemplateFile)
	upgradeTags := getTagsFromYaml(catalog.workspace)
	tags := catalog.getTags()
	tbb := catalog.TagsByBranch(tags)

	var cowpokeRequests []*http.Request
	var catalogCreationCheckRequests []*http.Request

	fmt.Println("Creating Catalog Templates for:")
	for branch := range tbb.branches {
		var count int
		var last *Tag

		// create branch dir
		branchDir := fmt.Sprintf("./templates/%s", branch)
		if !exists(branchDir) {
			os.Mkdir(branchDir, 0755)
		}

		// sort semver so we can count builds in a feature branch
		var vKeys []semver.Version
		for k := range tbb.branches[branch].versions {
			version, err := semver.Parse(k)
			if err != nil {
				fmt.Printf("Error parsing version %v \n", err)
				continue
			}
			vKeys = append(vKeys, version)
		}
		semver.Sort(vKeys)
		for _, version := range vKeys {
			// sort builds to count in order
			var bKeys []int
			ver := version.String()
			for k := range tbb.branches[branch].versions[ver].builds {
				bKeys = append(bKeys, k)
			}
			sort.Ints(bKeys)

			for _, build := range bKeys {
				tbb.branches[branch].versions[ver].builds[build].Count = count

				// create dir structure
				buildDir := fmt.Sprintf("%s/%d", branchDir, count)
				if !exists(buildDir) {
					fmt.Printf("  %d:%s %s-%d\n", count, branch, ver, build)
					os.Mkdir(buildDir, 0755)
				}

				// create docker-compose.yml and rancher-compose.yml from template
				// don't generate files if they already exist
				dockerComposeTarget := fmt.Sprintf("%s/docker-compose.yml", buildDir)
				if !exists(dockerComposeTarget) {
					catalog.executeTemplate(dockerComposeTarget, dockerComposeTmpl, tbb.branches[branch].versions[ver].builds[build])
				}
				rancherComposeTarget := fmt.Sprintf("%s/rancher-compose.yml", buildDir)
				if !exists(rancherComposeTarget) {
					catalog.executeTemplate(rancherComposeTarget, rancherComposeTmpl, tbb.branches[branch].versions[ver].builds[build])
				}

				last = tbb.branches[branch].versions[ver].builds[build]
				count++
			}
			if stringInSlice(last.Tag, upgradeTags) {
				//count was already incremented so it needs to be decremented for the cowpoke request.
				//it is important for iteration that there be the same number of elements in both of these arrays
				//Therefore even if buildCatalogCheckRequest returns nil we add it to the slice. The nil check happens doRequest
				catalogCreationCheckRequests = append(catalogCreationCheckRequests, buildCatalogCreationCheckRequest(catalog.vargs.CatalogRepo, branch, count-1, catalog.vargs.GitHubToken))
				cowpokeRequests = append(cowpokeRequests, cowpokeRequest(count-1, branch, catalog.vargs.CatalogRepo, catalog.vargs.RancherCatalogName, catalog.vargs.GitHubToken, catalog.vargs.CowpokeURL, catalog.vargs.BearerToken))
			}

		}

		// create config.yml from temlplate
		configTarget := fmt.Sprintf("%s/config.yml", branchDir)
		catalog.executeTemplate(configTarget, configTmpl, last)

		// Icon file
		copyIcon(iconFileBase, branchDir)
	}
	// TODO: Delete dir/files if tags don't exist anymore. Need to maintian build dir numbering

	if catalog.gitChanged() {
		catalog.addCatalogRepo()
		catalog.commitCatalogRepo()
		catalog.pushCatalogRepo()
	}
	client := &http.Client{
		Timeout: time.Second * 60,
	}
	time.Sleep(3000 * time.Millisecond) //give github time to be consisitent
	for index, request := range cowpokeRequests {
		doRequest(catalogCreationCheckRequests[index], request, client)
	}
	fmt.Println("... Finished drone-rancher-catalog")
}