1
0
mirror of https://github.com/woodpecker-ci/woodpecker.git synced 2024-12-12 08:23:48 +02:00
woodpecker/server/build.go

626 lines
15 KiB
Go
Raw Normal View History

2018-02-20 00:24:10 +02:00
// Copyright 2018 Drone.IO Inc.
2018-03-21 15:02:17 +02:00
//
2018-02-20 00:24:10 +02:00
// 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
2018-03-21 15:02:17 +02:00
//
2018-02-20 00:24:10 +02:00
// http://www.apache.org/licenses/LICENSE-2.0
2018-03-21 15:02:17 +02:00
//
2018-02-20 00:24:10 +02:00
// 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.
2016-05-02 21:21:25 +02:00
package server
2016-03-31 08:24:47 +02:00
import (
2018-01-18 19:26:28 +02:00
"bytes"
2017-03-05 13:05:16 +02:00
"context"
"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"
2019-06-01 10:17:02 +02:00
"github.com/gin-gonic/gin"
2019-04-06 15:44:04 +02:00
"github.com/laszlocph/drone-oss-08/cncd/queue"
2019-04-04 20:51:20 +02:00
"github.com/laszlocph/drone-oss-08/remote"
"github.com/laszlocph/drone-oss-08/shared/httputil"
"github.com/laszlocph/drone-oss-08/store"
2016-03-31 08:24:47 +02:00
2019-04-04 20:51:20 +02:00
"github.com/laszlocph/drone-oss-08/model"
"github.com/laszlocph/drone-oss-08/router/middleware/session"
2016-03-31 08:24:47 +02:00
)
func GetBuilds(c *gin.Context) {
repo := session.Repo(c)
page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
builds, err := store.GetBuildList(c, repo, page)
2016-03-31 08:24:47 +02:00
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-07-26 23:58:44 +02:00
files, _ := store.FromContext(c).FileList(build)
2017-04-02 16:13:26 +02:00
procs, _ := store.FromContext(c).ProcList(build)
build.Procs = model.Tree(procs)
2017-07-26 23:58:44 +02:00
build.Files = files
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-08-25 02:03:11 +02:00
ppid, _ := strconv.Atoi(c.Params.ByName("pid"))
2017-04-03 11:34:37 +02:00
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
2017-08-25 02:03:11 +02:00
c.Header("Content-Type", "application/json")
io.Copy(c.Writer, rc)
}
func GetProcLogs(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"))
pid, _ := strconv.Atoi(c.Params.ByName("pid"))
build, err := store.GetBuildNumber(c, repo, num)
if err != nil {
c.AbortWithError(404, err)
return
}
proc, err := store.FromContext(c).ProcFind(build, pid)
if err != nil {
c.AbortWithError(404, err)
return
}
rc, err := store.FromContext(c).LogFind(proc)
if err != nil {
c.AbortWithError(404, err)
return
}
defer rc.Close()
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
Config.Services.Queue.Error(context.Background(), fmt.Sprint(proc.ID), queue.ErrCancel)
c.String(204, "")
2016-03-31 08:24:47 +02:00
}
2017-08-01 18:57:01 +02:00
// ZombieKill kills zombie processes stuck in an infinite pending
// or running state. This can only be invoked by administrators and
// may have negative effects.
func ZombieKill(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"))
build, err := store.GetBuildNumber(c, repo, num)
if err != nil {
c.AbortWithError(404, err)
return
}
procs, err := store.FromContext(c).ProcList(build)
if err != nil {
c.AbortWithError(404, err)
return
}
if build.Status != model.StatusRunning {
c.String(400, "Cannot force cancel a non-running build")
return
}
for _, proc := range procs {
if proc.Running() {
proc.State = model.StatusKilled
proc.ExitCode = 137
proc.Stopped = time.Now().Unix()
if proc.Started == 0 {
proc.Started = proc.Stopped
}
}
}
for _, proc := range procs {
store.FromContext(c).ProcUpdate(proc)
Config.Services.Queue.Error(context.Background(), fmt.Sprint(proc.ID), queue.ErrCancel)
}
build.Status = model.StatusKilled
build.Finished = time.Now().Unix()
store.FromContext(c).UpdateBuild(build)
c.String(204, "")
}
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
// fetch the build file from the database
configs, err := Config.Storage.Config.ConfigsForBuild(build.ID)
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)
2017-05-19 23:36:08 +02:00
secs, err := Config.Services.Secrets.SecretListBuild(repo, build)
2017-03-18 13:25:53 +02:00
if err != nil {
logrus.Debugf("Error getting secrets for %s#%d. %s", repo.FullName, build.Number, err)
}
regs, err := Config.Services.Registries.RegistryList(repo)
2017-04-06 18:04:25 +02:00
if err != nil {
logrus.Debugf("Error getting registry credentials for %s#%d. %s", repo.FullName, build.Number, err)
}
2017-06-26 21:27:53 +02:00
envs := map[string]string{}
if Config.Services.Environ != nil {
globals, _ := Config.Services.Environ.EnvironList(repo)
for _, global := range globals {
envs[global.Name] = global.Value
}
}
2017-03-18 13:25:53 +02:00
2019-06-13 17:38:19 +02:00
var yamls []*remote.FileMeta
2019-06-07 10:40:16 +02:00
for _, y := range configs {
2019-06-13 17:38:19 +02:00
yamls = append(yamls, &remote.FileMeta{Data: []byte(y.Data), Name: y.Name})
2019-06-07 10:40:16 +02:00
}
2019-06-01 10:17:02 +02:00
b := procBuilder{
2017-03-18 13:25:53 +02:00
Repo: repo,
Curr: build,
Last: last,
Netrc: netrc,
Secs: secs,
2017-04-06 18:04:25 +02:00
Regs: regs,
2017-03-18 13:25:53 +02:00
Link: httputil.GetURL(c.Request),
2019-06-07 10:40:16 +02:00
Yamls: yamls,
2017-06-26 21:27:53 +02:00
Envs: envs,
2017-03-18 13:25:53 +02:00
}
2019-06-01 10:27:28 +02:00
buildItems, err := b.Build()
2017-03-18 13:25:53 +02:00
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
}
2019-06-01 10:27:28 +02:00
err = store.FromContext(c).ProcCreate(build.Procs)
if err != nil {
logrus.Errorf("error persisting procs %s/%d: %s", repo.FullName, build.Number, err)
2017-03-18 13:25:53 +02:00
}
2017-03-18 10:49:27 +02:00
defer func() {
for _, item := range buildItems {
uri := fmt.Sprintf("%s/%s/%d", httputil.GetURL(c.Request), repo.FullName, build.Number)
if len(buildItems) > 1 {
err = remote_.Status(user, repo, build, uri, item.Proc)
} else {
err = remote_.Status(user, repo, build, uri, nil)
}
if err != nil {
logrus.Errorf("error setting commit status for %s/%d: %v", repo.FullName, build.Number, err)
}
}
}()
2019-06-01 10:27:28 +02:00
publishToTopic(c, build, repo)
queueBuild(build, repo, buildItems)
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, nil)
2017-03-18 13:25:53 +02:00
if err != nil {
logrus.Errorf("error setting commit status for %s/%d: %v", repo.FullName, build.Number, err)
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
2019-06-01 12:52:02 +02:00
// PostBuild restarts a build
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)
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
}
2017-09-15 00:33:12 +02:00
switch build.Status {
case model.StatusDeclined,
model.StatusBlocked:
2017-09-15 00:33:12 +02:00
c.String(500, "cannot restart a build with status %s", build.Status)
return
}
2017-03-14 17:56:22 +02:00
// 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
configs, err := Config.Storage.Config.ConfigsForBuild(build.ID)
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
}
build.ID = 0
build.Number = 0
build.Parent = num
build.Status = model.StatusPending
build.Started = 0
build.Finished = 0
build.Enqueued = time.Now().UTC().Unix()
build.Error = ""
build.Deploy = c.DefaultQuery("deploy_to", build.Deploy)
2017-09-08 02:43:33 +02:00
event := c.DefaultQuery("event", build.Event)
if event == model.EventPush ||
event == model.EventPull ||
event == model.EventTag ||
event == model.EventDeploy {
build.Event = event
}
err = store.CreateBuild(c, build)
if err != nil {
c.String(500, err.Error())
return
2017-03-14 17:56:22 +02:00
}
2019-06-13 17:38:19 +02:00
err = persistBuildConfigs(configs, build.ID)
if err != nil {
logrus.Errorf("failure to persist build config for %s. %s", repo.FullName, err)
c.AbortWithError(500, err)
return
}
2017-03-14 17:56:22 +02:00
// 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]
}
}
// get the previous build so that we can send
// on status change notifications
last, _ := store.GetBuildLastBefore(c, repo, build.Branch, build.ID)
2017-05-19 23:36:08 +02:00
secs, err := Config.Services.Secrets.SecretListBuild(repo, build)
2017-03-14 17:56:22 +02:00
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
}
regs, err := Config.Services.Registries.RegistryList(repo)
2017-04-06 18:04:25 +02:00
if err != nil {
logrus.Debugf("Error getting registry credentials for %s#%d. %s", repo.FullName, build.Number, err)
}
2017-06-26 21:27:53 +02:00
if Config.Services.Environ != nil {
globals, _ := Config.Services.Environ.EnvironList(repo)
for _, global := range globals {
buildParams[global.Name] = global.Value
}
}
2017-03-14 17:56:22 +02:00
2019-06-13 17:38:19 +02:00
var yamls []*remote.FileMeta
2019-06-07 10:40:16 +02:00
for _, y := range configs {
2019-06-13 17:38:19 +02:00
yamls = append(yamls, &remote.FileMeta{Data: []byte(y.Data), Name: y.Name})
2019-06-07 10:40:16 +02:00
}
2019-06-01 10:17:02 +02:00
b := procBuilder{
2017-03-14 17:56:22 +02:00
Repo: repo,
Curr: build,
Last: last,
Netrc: netrc,
Secs: secs,
2017-04-06 18:04:25 +02:00
Regs: regs,
2017-03-14 17:56:22 +02:00
Link: httputil.GetURL(c.Request),
2019-06-07 10:40:16 +02:00
Yamls: yamls,
Envs: buildParams,
2017-03-14 17:56:22 +02:00
}
2019-06-01 10:27:28 +02:00
buildItems, err := b.Build()
2017-03-14 17:56:22 +02:00
if err != nil {
build.Status = model.StatusError
build.Started = time.Now().Unix()
build.Finished = build.Started
build.Error = err.Error()
c.JSON(500, build)
2017-03-14 17:56:22 +02:00
return
}
err = store.FromContext(c).ProcCreate(build.Procs)
if err != nil {
logrus.Errorf("cannot restart %s#%d: %s", repo.FullName, build.Number, err)
build.Status = model.StatusError
build.Started = time.Now().Unix()
build.Finished = build.Started
build.Error = err.Error()
c.JSON(500, build)
return
}
c.JSON(202, build)
2019-06-01 10:27:28 +02:00
publishToTopic(c, build, repo)
queueBuild(build, repo, buildItems)
2017-03-14 17:56:22 +02:00
}
2018-01-18 19:26:28 +02:00
func DeleteBuildLogs(c *gin.Context) {
repo := session.Repo(c)
user := session.User(c)
2018-01-18 19:26:28 +02:00
num, _ := strconv.Atoi(c.Params.ByName("number"))
build, err := store.GetBuildNumber(c, repo, num)
if err != nil {
c.AbortWithError(404, err)
return
}
procs, err := store.FromContext(c).ProcList(build)
if err != nil {
c.AbortWithError(404, err)
return
}
switch build.Status {
case model.StatusRunning, model.StatusPending:
c.String(400, "Cannot delete logs for a pending or running build")
return
}
for _, proc := range procs {
2018-01-18 20:20:42 +02:00
t := time.Now().UTC()
buf := bytes.NewBufferString(fmt.Sprintf(deleteStr, proc.Name, user.Login, t.Format(time.UnixDate)))
2018-01-18 19:26:28 +02:00
lerr := store.FromContext(c).LogSave(proc, buf)
if lerr != nil {
err = lerr
}
}
if err != nil {
c.String(400, "There was a problem deleting your logs. %s", err)
return
}
c.String(204, "")
}
2019-06-13 17:38:19 +02:00
func persistBuildConfigs(configs []*model.Config, buildID int64) error {
for _, conf := range configs {
buildConfig := &model.BuildConfig{
ConfigID: conf.ID,
BuildID: buildID,
}
err := Config.Storage.Config.BuildConfigCreate(buildConfig)
if err != nil {
return err
}
}
return nil
}
2018-01-18 19:26:28 +02:00
var deleteStr = `[
{
"proc": %q,
"pos": 0,
2018-01-18 20:08:11 +02:00
"out": "logs purged by %s on %s\n"
2018-01-18 19:26:28 +02:00
}
]`