Exemplo n.º 1
0
Arquivo: build.go Projeto: armab/drone
// TODO this has gotten a bit out of hand. refactor input params
func run(path, identity, dockerhost, dockercert, dockerkey string, publish, deploy, privileged bool) (int, error) {
	dockerClient, err := docker.NewHostCertFile(dockerhost, dockercert, dockerkey)
	if err != nil {
		log.Err(err.Error())
		return EXIT_STATUS, err
	}

	// parse the private environment variables
	envs := getParamMap("DRONE_ENV_")

	// parse the Drone yml file
	s, err := script.ParseBuildFile(path, envs)
	if err != nil {
		log.Err(err.Error())
		return EXIT_STATUS, err
	}

	// inject private environment variables into build script
	for key, val := range envs {
		s.Env = append(s.Env, key+"="+val)
	}

	if deploy == false {
		s.Deploy = nil
	}
	if publish == false {
		s.Publish = nil
	}

	// get the repository root directory
	dir := filepath.Dir(path)
	code := repo.Repo{
		Name:   filepath.Base(dir),
		Branch: "HEAD", // should we do this?
		Path:   dir,
	}

	// does the local repository match the
	// $GOPATH/src/{package} pattern? This is
	// important so we know the target location
	// where the code should be copied inside
	// the container.
	if gopath, ok := getRepoPath(dir); ok {
		code.Dir = gopath

	} else if gopath, ok := getGoPath(dir); ok {
		// in this case we found a GOPATH and
		// reverse engineered the package path
		code.Dir = gopath

	} else {
		// otherwise just use directory name
		code.Dir = filepath.Base(dir)
	}

	// this is where the code gets uploaded to the container
	// TODO move this code to the build package
	code.Dir = filepath.Join("/var/cache/drone/src", filepath.Clean(code.Dir))

	// ssh key to import into container
	var key []byte
	if len(identity) != 0 {
		key, err = ioutil.ReadFile(identity)
		if err != nil {
			fmt.Printf("[Error] Could not find or read identity file %s\n", identity)
			return EXIT_STATUS, err
		}
	}

	// loop through and create builders
	builder := build.New(dockerClient)
	builder.Build = s
	builder.Repo = &code
	builder.Key = key
	builder.Stdout = os.Stdout
	builder.Timeout = 300 * time.Minute
	builder.Privileged = privileged

	// execute the build
	if err := builder.Run(); err != nil {
		log.Errf("Error executing build: %s", err.Error())
		return EXIT_STATUS, err
	}

	fmt.Printf("\nDrone Build Results \033[90m(%s)\033[0m\n", dir)

	// loop through and print results

	build := builder.Build
	res := builder.BuildState
	duration := time.Duration(res.Finished - res.Started)
	switch {
	case builder.BuildState.ExitCode == 0:
		fmt.Printf(" \033[32m\u2713\033[0m %v \033[90m(%v)\033[0m\n", build.Name, humanizeDuration(duration*time.Second))
	case builder.BuildState.ExitCode != 0:
		fmt.Printf(" \033[31m\u2717\033[0m %v \033[90m(%v)\033[0m\n", build.Name, humanizeDuration(duration*time.Second))
	}

	return builder.BuildState.ExitCode, nil
}
Exemplo n.º 2
0
func (d *Docker) Do(c context.Context, r *worker.Work) {

	// ensure that we can recover from any panics to
	// avoid bringing down the entire application.
	defer func() {
		if e := recover(); e != nil {
			log.Printf("%s: %s", e, debug.Stack())
		}
	}()

	// mark the build as Started and update the database
	r.Commit.Status = model.StatusStarted
	r.Commit.Started = time.Now().UTC().Unix()

	datastore.PutCommit(c, r.Commit)

	// notify all listeners that the build is started
	commitc := pubsub.Register(c, "_global")
	commitc.Publish(r)
	stdoutc := pubsub.RegisterOpts(c, r.Commit.ID, pubsub.ConsoleOpts)
	defer pubsub.Unregister(c, r.Commit.ID)

	// create a special buffer that will also
	// write to a websocket channel
	buf := pubsub.NewBuffer(stdoutc)

	// parse the parameters and build script. The script has already
	// been parsed in the hook, so we can be confident it will succeed.
	// that being said, we should clean this up
	params, err := r.Repo.ParamMap()
	if err != nil {
		log.Printf("Error parsing PARAMS for %s/%s, Err: %s", r.Repo.Owner, r.Repo.Name, err.Error())
	}
	script, err := script.ParseBuild(script.Inject(r.Commit.Config, params))
	if err != nil {
		log.Printf("Error parsing YAML for %s/%s, Err: %s", r.Repo.Owner, r.Repo.Name, err.Error())
	}

	// TODO: handle error better?
	buildNumber, err := datastore.GetBuildNumber(c, r.Commit)
	if err != nil {
		log.Printf("Unable to fetch build number, Err: %s", err.Error())
	}
	script.Env = append(script.Env, fmt.Sprintf("DRONE_BUILD_NUMBER=%d", buildNumber))
	script.Env = append(script.Env, fmt.Sprintf("CI_BUILD_NUMBER=%d", buildNumber))

	path := r.Repo.Host + "/" + r.Repo.Owner + "/" + r.Repo.Name
	repo := &repo.Repo{
		Name:    path,
		Path:    r.Repo.CloneURL,
		Branch:  r.Commit.Branch,
		Commit:  r.Commit.Sha,
		PR:      r.Commit.PullRequest,
		Private: r.Repo.Private,
		Dir:     filepath.ToSlash(filepath.Join("/var/cache/drone/src", git.GitPath(script.Git, path))),
		Depth:   git.GitDepth(script.Git),
	}

	// append private parameters to the environment
	// variable section of the .drone.yml file, if
	// this is trusted
	if params != nil && repo.IsTrusted() {
		for k, v := range params {
			script.Env = append(script.Env, k+"="+v)
		}
	}

	priorCommit, _ := datastore.GetCommitPrior(c, r.Commit)

	// send all "started" notifications
	if script.Notifications == nil {
		script.Notifications = &notify.Notification{}
	}
	script.Notifications.Send(&model.Request{
		User:   r.User,
		Repo:   r.Repo,
		Commit: r.Commit,
		Host:   r.Host,
		Prior:  priorCommit,
	})

	// create an instance of the Docker builder
	builder := build.New(d.docker)
	builder.Build = script
	builder.Repo = repo
	builder.Stdout = buf
	builder.Timeout = time.Duration(r.Repo.Timeout) * time.Second
	builder.Privileged = r.Repo.Privileged

	if repo.IsTrusted() {
		builder.Key = []byte(r.Repo.PrivateKey)
	}

	// run the build
	err = builder.Run()

	// update the build status based on the results
	// from the build runner.
	switch {
	case err != nil:
		r.Commit.Status = model.StatusError
		log.Printf("Error building %s, Err: %s", r.Commit.Sha, err)
		buf.WriteString(err.Error())
	case builder.BuildState == nil:
		r.Commit.Status = model.StatusFailure
	case builder.BuildState.ExitCode != 0:
		r.Commit.Status = model.StatusFailure
	default:
		r.Commit.Status = model.StatusSuccess
	}

	// calcualte the build finished and duration details and
	// update the commit
	r.Commit.Finished = time.Now().UTC().Unix()
	r.Commit.Duration = (r.Commit.Finished - r.Commit.Started)
	datastore.PutCommit(c, r.Commit)
	blobstore.Put(c, filepath.Join(r.Repo.Host, r.Repo.Owner, r.Repo.Name, r.Commit.Branch, r.Commit.Sha), buf.Bytes())

	// notify all listeners that the build is finished
	commitc.Publish(r)

	priorCommit, _ = datastore.GetCommitPrior(c, r.Commit)

	// send all "finished" notifications
	script.Notifications.Send(&model.Request{
		User:   r.User,
		Repo:   r.Repo,
		Commit: r.Commit,
		Host:   r.Host,
		Prior:  priorCommit,
	})
}