1
0
mirror of https://github.com/woodpecker-ci/woodpecker.git synced 2024-11-30 08:06:52 +02:00
woodpecker/server/build.go

561 lines
13 KiB
Go
Raw Normal View History

2016-05-02 21:21:25 +02:00
package server
2016-03-31 08:24:47 +02:00
import (
2017-03-05 13:05:16 +02:00
"context"
2017-03-14 17:56:22 +02:00
"encoding/json"
2017-03-05 13:05:16 +02:00
"fmt"
2016-09-28 03:30:28 +02:00
"io"
2016-03-31 08:24:47 +02:00
"net/http"
"strconv"
"time"
2017-03-18 11:16:39 +02:00
"github.com/Sirupsen/logrus"
2017-03-14 17:56:22 +02:00
"github.com/cncd/pipeline/pipeline/rpc"
"github.com/cncd/pubsub"
2017-03-05 13:05:16 +02:00
"github.com/cncd/queue"
2016-03-31 08:24:47 +02:00
"github.com/drone/drone/remote"
"github.com/drone/drone/shared/httputil"
"github.com/drone/drone/store"
"github.com/gin-gonic/gin"
"github.com/drone/drone/model"
"github.com/drone/drone/router/middleware/session"
)
func GetBuilds(c *gin.Context) {
repo := session.Repo(c)
builds, err := store.GetBuildList(c, repo)
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
2016-06-14 23:01:20 +02:00
c.JSON(http.StatusOK, builds)
2016-03-31 08:24:47 +02:00
}
func GetBuild(c *gin.Context) {
if c.Param("number") == "latest" {
GetBuildLast(c)
return
}
repo := session.Repo(c)
num, err := strconv.Atoi(c.Param("number"))
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
build, err := store.GetBuildNumber(c, repo, num)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
2017-04-02 16:13:26 +02:00
procs, _ := store.FromContext(c).ProcList(build)
build.Procs = model.Tree(procs)
2016-03-31 08:24:47 +02:00
2017-04-02 16:13:26 +02:00
c.JSON(http.StatusOK, build)
2016-03-31 08:24:47 +02:00
}
func GetBuildLast(c *gin.Context) {
repo := session.Repo(c)
branch := c.DefaultQuery("branch", repo.Branch)
build, err := store.GetBuildLast(c, repo, branch)
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
2017-04-02 16:13:26 +02:00
procs, _ := store.FromContext(c).ProcList(build)
build.Procs = model.Tree(procs)
c.JSON(http.StatusOK, build)
2016-03-31 08:24:47 +02:00
}
func GetBuildLogs(c *gin.Context) {
repo := session.Repo(c)
// parse the build number and job sequence number from
// the repquest parameter.
num, _ := strconv.Atoi(c.Params.ByName("number"))
2017-04-03 11:34:37 +02:00
ppid, _ := strconv.Atoi(c.Params.ByName("ppid"))
name := c.Params.ByName("proc")
2016-03-31 08:24:47 +02:00
build, err := store.GetBuildNumber(c, repo, num)
if err != nil {
c.AbortWithError(404, err)
return
}
2017-04-03 11:34:37 +02:00
proc, err := store.FromContext(c).ProcChild(build, ppid, name)
2016-03-31 08:24:47 +02:00
if err != nil {
c.AbortWithError(404, err)
return
}
2017-04-03 11:34:37 +02:00
rc, err := store.FromContext(c).LogFind(proc)
2016-03-31 08:24:47 +02:00
if err != nil {
c.AbortWithError(404, err)
return
}
2017-04-02 16:13:26 +02:00
defer rc.Close()
2016-05-11 09:36:01 +02:00
2016-06-14 23:01:20 +02:00
c.Header("Content-Type", "application/json")
2017-04-02 16:13:26 +02:00
io.Copy(c.Writer, rc)
2016-03-31 08:24:47 +02:00
}
func DeleteBuild(c *gin.Context) {
repo := session.Repo(c)
// parse the build number and job sequence number from
// the repquest parameter.
num, _ := strconv.Atoi(c.Params.ByName("number"))
seq, _ := strconv.Atoi(c.Params.ByName("job"))
build, err := store.GetBuildNumber(c, repo, num)
if err != nil {
c.AbortWithError(404, err)
return
}
2017-04-02 16:13:26 +02:00
proc, err := store.FromContext(c).ProcFind(build, seq)
2016-03-31 08:24:47 +02:00
if err != nil {
c.AbortWithError(404, err)
return
}
2017-04-02 16:13:26 +02:00
if proc.State != model.StatusRunning {
2016-07-13 23:25:40 +02:00
c.String(400, "Cannot cancel a non-running build")
return
}
2017-04-02 16:13:26 +02:00
proc.State = model.StatusKilled
proc.Stopped = time.Now().Unix()
if proc.Started == 0 {
proc.Started = proc.Stopped
2016-07-13 23:25:40 +02:00
}
2017-04-02 16:13:26 +02:00
proc.ExitCode = 137
// TODO cancel child procs
store.FromContext(c).ProcUpdate(proc)
2016-07-13 23:25:40 +02:00
2017-04-02 16:13:26 +02:00
config.queue.Error(context.Background(), fmt.Sprint(proc.ID), queue.ErrCancel)
c.String(204, "")
2016-03-31 08:24:47 +02:00
}
2017-03-18 10:49:27 +02:00
func PostApproval(c *gin.Context) {
var (
2017-03-18 13:25:53 +02:00
remote_ = remote.FromContext(c)
repo = session.Repo(c)
user = session.User(c)
num, _ = strconv.Atoi(
2017-03-18 10:49:27 +02:00
c.Params.ByName("number"),
)
)
build, err := store.GetBuildNumber(c, repo, num)
if err != nil {
c.AbortWithError(404, err)
return
}
if build.Status != model.StatusBlocked {
c.String(500, "cannot decline a build with status %s", build.Status)
return
}
build.Status = model.StatusPending
build.Reviewed = time.Now().Unix()
build.Reviewer = user.Login
2017-03-18 13:25:53 +02:00
//
//
// This code is copied pasted until I have a chance
// to refactor into a proper function. Lots of changes
// and technical debt. No judgement please!
//
//
// fetch the build file from the database
2017-03-19 10:44:57 +02:00
raw, err := remote_.File(user, repo, build, repo.Config)
2017-03-18 13:25:53 +02:00
if err != nil {
logrus.Errorf("failure to get build config for %s. %s", repo.FullName, err)
c.AbortWithError(404, err)
return
}
netrc, err := remote_.Netrc(user, repo)
if err != nil {
c.String(500, "Failed to generate netrc file. %s", err)
return
}
if uerr := store.UpdateBuild(c, build); err != nil {
c.String(500, "error updating build. %s", uerr)
return
}
c.JSON(200, build)
// get the previous build so that we can send
// on status change notifications
last, _ := store.GetBuildLastBefore(c, repo, build.Branch, build.ID)
secs, err := store.GetMergedSecretList(c, repo)
if err != nil {
logrus.Debugf("Error getting secrets for %s#%d. %s", repo.FullName, build.Number, err)
}
defer func() {
uri := fmt.Sprintf("%s/%s/%d", httputil.GetURL(c.Request), repo.FullName, build.Number)
err = remote_.Status(user, repo, build, uri)
if err != nil {
logrus.Errorf("error setting commit status for %s/%d", repo.FullName, build.Number)
}
}()
b := builder{
Repo: repo,
Curr: build,
Last: last,
Netrc: netrc,
Secs: secs,
Link: httputil.GetURL(c.Request),
Yaml: string(raw),
}
items, err := b.Build()
if err != nil {
build.Status = model.StatusError
build.Started = time.Now().Unix()
build.Finished = build.Started
build.Error = err.Error()
store.UpdateBuild(c, build)
2017-03-18 10:49:27 +02:00
return
}
2017-04-02 16:13:26 +02:00
var pcounter = len(items)
2017-03-18 13:25:53 +02:00
for _, item := range items {
2017-04-02 16:13:26 +02:00
build.Procs = append(build.Procs, item.Proc)
item.Proc.BuildID = build.ID
for _, stage := range item.Config.Stages {
var gid int
for _, step := range stage.Steps {
pcounter++
if gid == 0 {
gid = pcounter
}
proc := &model.Proc{
BuildID: build.ID,
Name: step.Alias,
PID: pcounter,
PPID: item.Proc.PID,
PGID: gid,
State: model.StatusPending,
}
build.Procs = append(build.Procs, proc)
}
}
2017-03-18 13:25:53 +02:00
}
2017-04-02 16:13:26 +02:00
store.FromContext(c).ProcCreate(build.Procs)
2017-03-18 13:25:53 +02:00
//
// publish topic
//
2017-04-04 11:30:06 +02:00
buildCopy := *build
buildCopy.Procs = model.Tree(buildCopy.Procs)
2017-03-18 13:25:53 +02:00
message := pubsub.Message{
Labels: map[string]string{
"repo": repo.FullName,
"private": strconv.FormatBool(repo.IsPrivate),
},
}
message.Data, _ = json.Marshal(model.Event{
Type: model.Enqueued,
Repo: *repo,
2017-04-04 11:30:06 +02:00
Build: buildCopy,
2017-03-18 13:25:53 +02:00
})
// TODO remove global reference
config.pubsub.Publish(c, "topic/events", message)
2017-04-04 11:30:06 +02:00
2017-03-18 10:49:27 +02:00
//
2017-03-18 13:25:53 +02:00
// end publish topic
2017-03-18 10:49:27 +02:00
//
2017-03-18 13:25:53 +02:00
for _, item := range items {
task := new(queue.Task)
2017-04-02 16:13:26 +02:00
task.ID = fmt.Sprint(item.Proc.ID)
2017-03-18 13:25:53 +02:00
task.Labels = map[string]string{}
task.Labels["platform"] = item.Platform
for k, v := range item.Labels {
task.Labels[k] = v
}
task.Data, _ = json.Marshal(rpc.Pipeline{
2017-04-02 16:13:26 +02:00
ID: fmt.Sprint(item.Proc.ID),
2017-03-18 13:25:53 +02:00
Config: item.Config,
Timeout: b.Repo.Timeout,
})
config.logger.Open(context.Background(), task.ID)
config.queue.Push(context.Background(), task)
}
2017-03-18 10:49:27 +02:00
}
func PostDecline(c *gin.Context) {
var (
2017-03-18 11:16:39 +02:00
remote_ = remote.FromContext(c)
repo = session.Repo(c)
user = session.User(c)
num, _ = strconv.Atoi(
2017-03-18 10:49:27 +02:00
c.Params.ByName("number"),
)
)
build, err := store.GetBuildNumber(c, repo, num)
if err != nil {
c.AbortWithError(404, err)
return
}
if build.Status != model.StatusBlocked {
c.String(500, "cannot decline a build with status %s", build.Status)
return
}
build.Status = model.StatusDeclined
build.Reviewed = time.Now().Unix()
build.Reviewer = user.Login
2017-03-18 11:16:39 +02:00
err = store.UpdateBuild(c, build)
if err != nil {
2017-03-18 10:49:27 +02:00
c.String(500, "error updating build. %s", err)
return
}
2017-03-18 11:16:39 +02:00
2017-03-18 13:25:53 +02:00
uri := fmt.Sprintf("%s/%s/%d", httputil.GetURL(c.Request), repo.FullName, build.Number)
err = remote_.Status(user, repo, build, uri)
if err != nil {
logrus.Errorf("error setting commit status for %s/%d", repo.FullName, build.Number)
2017-03-18 11:16:39 +02:00
}
2017-03-18 10:49:27 +02:00
c.JSON(200, build)
}
func GetBuildQueue(c *gin.Context) {
out, err := store.GetBuildQueue(c)
if err != nil {
c.String(500, "Error getting build queue. %s", err)
return
}
c.JSON(200, out)
}
2016-09-28 03:30:28 +02:00
2017-03-14 17:56:22 +02:00
//
//
//
//
//
//
2017-03-16 12:14:02 +02:00
func PostBuild(c *gin.Context) {
2017-03-14 17:56:22 +02:00
remote_ := remote.FromContext(c)
repo := session.Repo(c)
fork := c.DefaultQuery("fork", "false")
num, err := strconv.Atoi(c.Param("number"))
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
user, err := store.GetUser(c, repo.UserID)
if err != nil {
2017-03-18 11:16:39 +02:00
logrus.Errorf("failure to find repo owner %s. %s", repo.FullName, err)
2017-03-14 17:56:22 +02:00
c.AbortWithError(500, err)
return
}
build, err := store.GetBuildNumber(c, repo, num)
if err != nil {
2017-03-18 11:16:39 +02:00
logrus.Errorf("failure to get build %d. %s", num, err)
2017-03-14 17:56:22 +02:00
c.AbortWithError(404, err)
return
}
// if the remote has a refresh token, the current access token
// may be stale. Therefore, we should refresh prior to dispatching
// the job.
if refresher, ok := remote_.(remote.Refresher); ok {
ok, _ := refresher.Refresh(user)
if ok {
store.UpdateUser(c, user)
}
}
// fetch the .drone.yml file from the database
2017-03-19 10:44:57 +02:00
raw, err := remote_.File(user, repo, build, repo.Config)
2017-03-14 17:56:22 +02:00
if err != nil {
2017-03-18 11:16:39 +02:00
logrus.Errorf("failure to get build config for %s. %s", repo.FullName, err)
2017-03-14 17:56:22 +02:00
c.AbortWithError(404, err)
return
}
netrc, err := remote_.Netrc(user, repo)
if err != nil {
2017-03-18 11:16:39 +02:00
logrus.Errorf("failure to generate netrc for %s. %s", repo.FullName, err)
2017-03-14 17:56:22 +02:00
c.AbortWithError(500, err)
return
}
2017-04-02 16:13:26 +02:00
procs, err := store.FromContext(c).ProcList(build)
2017-03-14 17:56:22 +02:00
if err != nil {
2017-04-02 16:13:26 +02:00
logrus.Errorf("failure to get build %d procs. %s", build.Number, err)
2017-03-14 17:56:22 +02:00
c.AbortWithError(404, err)
return
}
// must not restart a running build
if build.Status == model.StatusPending || build.Status == model.StatusRunning {
c.String(409, "Cannot re-start a started build")
return
}
// forking the build creates a duplicate of the build
// and then executes. This retains prior build history.
if forkit, _ := strconv.ParseBool(fork); forkit {
build.ID = 0
build.Number = 0
build.Parent = num
2017-04-02 16:13:26 +02:00
for _, proc := range procs {
proc.ID = 0
proc.BuildID = 0
2017-03-14 17:56:22 +02:00
}
2017-04-02 16:13:26 +02:00
err := store.CreateBuild(c, build, procs...)
2017-03-14 17:56:22 +02:00
if err != nil {
c.String(500, err.Error())
return
}
event := c.DefaultQuery("event", build.Event)
if event == model.EventPush ||
event == model.EventPull ||
event == model.EventTag ||
event == model.EventDeploy {
build.Event = event
}
build.Deploy = c.DefaultQuery("deploy_to", build.Deploy)
}
// Read query string parameters into buildParams, exclude reserved params
var buildParams = map[string]string{}
for key, val := range c.Request.URL.Query() {
switch key {
case "fork", "event", "deploy_to":
default:
// We only accept string literals, because build parameters will be
// injected as environment variables
buildParams[key] = val[0]
}
}
// todo move this to database tier
// and wrap inside a transaction
build.Status = model.StatusPending
build.Started = 0
build.Finished = 0
build.Enqueued = time.Now().UTC().Unix()
build.Error = ""
2017-04-02 16:13:26 +02:00
for _, proc := range procs {
2017-03-14 17:56:22 +02:00
for k, v := range buildParams {
2017-04-02 16:13:26 +02:00
proc.Environ[k] = v
2017-03-14 17:56:22 +02:00
}
2017-04-02 16:13:26 +02:00
proc.Error = ""
proc.State = model.StatusPending
proc.Started = 0
proc.Stopped = 0
proc.ExitCode = 0
proc.Machine = ""
store.FromContext(c).ProcUpdate(proc)
2017-03-14 17:56:22 +02:00
}
err = store.UpdateBuild(c, build)
if err != nil {
c.AbortWithStatus(500)
return
}
c.JSON(202, build)
// get the previous build so that we can send
// on status change notifications
last, _ := store.GetBuildLastBefore(c, repo, build.Branch, build.ID)
secs, err := store.GetMergedSecretList(c, repo)
if err != nil {
2017-03-18 11:16:39 +02:00
logrus.Debugf("Error getting secrets for %s#%d. %s", repo.FullName, build.Number, err)
2017-03-14 17:56:22 +02:00
}
b := builder{
Repo: repo,
Curr: build,
Last: last,
Netrc: netrc,
Secs: secs,
Link: httputil.GetURL(c.Request),
Yaml: string(raw),
}
items, err := b.Build()
if err != nil {
build.Status = model.StatusError
build.Started = time.Now().Unix()
build.Finished = build.Started
build.Error = err.Error()
return
}
for i, item := range items {
// TODO prevent possible index out of bounds
2017-04-02 16:13:26 +02:00
item.Proc.ID = procs[i].ID
build.Procs = append(build.Procs, item.Proc)
store.FromContext(c).ProcUpdate(item.Proc)
// TODO update child procs too!
2017-03-14 17:56:22 +02:00
}
//
// publish topic
//
2017-04-04 11:30:06 +02:00
buildCopy := *build
buildCopy.Procs = model.Tree(buildCopy.Procs)
2017-03-14 17:56:22 +02:00
message := pubsub.Message{
Labels: map[string]string{
"repo": repo.FullName,
"private": strconv.FormatBool(repo.IsPrivate),
},
}
message.Data, _ = json.Marshal(model.Event{
Type: model.Enqueued,
Repo: *repo,
2017-04-04 11:30:06 +02:00
Build: buildCopy,
2017-03-14 17:56:22 +02:00
})
// TODO remove global reference
config.pubsub.Publish(c, "topic/events", message)
//
// end publish topic
//
for _, item := range items {
task := new(queue.Task)
2017-04-02 16:13:26 +02:00
task.ID = fmt.Sprint(item.Proc.ID)
2017-03-14 17:56:22 +02:00
task.Labels = map[string]string{}
task.Labels["platform"] = item.Platform
for k, v := range item.Labels {
task.Labels[k] = v
}
task.Data, _ = json.Marshal(rpc.Pipeline{
2017-04-02 16:13:26 +02:00
ID: fmt.Sprint(item.Proc.ID),
2017-03-14 17:56:22 +02:00
Config: item.Config,
Timeout: b.Repo.Timeout,
})
config.logger.Open(context.Background(), task.ID)
config.queue.Push(context.Background(), task)
}
}