Skip to content

Commit

Permalink
handles build cancellation with sigterm
Browse files Browse the repository at this point in the history
  • Loading branch information
ericrenard committed May 28, 2019
1 parent 6522f01 commit 3e67276
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
26 changes: 25 additions & 1 deletion cmd/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ package cmd
import (
"fmt"
"log"
"os"
"os/signal"
"time"

"syscall"

"github.com/cheggaaa/pb"
"github.com/fatih/color"
"github.com/molotovtv/tc/internal/config"
Expand Down Expand Up @@ -40,6 +44,9 @@ var statusCmd = &cobra.Command{
func buildStatus(c config.Config, buildID string) {
bar := pb.StartNew(100)
var build *tc.Build
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM)
buildInterrupted := false
for {
var err error
build, err = tc.LastBuild(c, buildID)
Expand All @@ -52,9 +59,26 @@ func buildStatus(c config.Config, buildID string) {
}

bar.Set(int(build.PercentageComplete))
time.Sleep(time.Second)
select {
case <-signalChan:
buildInterrupted = true
break
case <-time.After(time.Second):
break
}
if buildInterrupted {
break
}
}
signal.Reset(os.Interrupt, syscall.SIGTERM)
bar.Finish()
if buildInterrupted {
if err := tc.CancelBuild(c, build.ID); err != nil {
log.Fatal(err)
}
color.Magenta("Build cancelled!")
return
}
if build == nil || build.Status != "SUCCESS" {
color.Red("Build failed!")
return
Expand Down
30 changes: 30 additions & 0 deletions tc/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io/ioutil"
"net/http"
"strings"

"github.com/molotovtv/tc/internal/config"
)
Expand Down Expand Up @@ -37,6 +38,35 @@ const (
BuildStatusFinished BuildState = "finished"
)

// CancelBuild ...
func CancelBuild(config config.Config, build int) error {
req, err := http.NewRequest(
http.MethodPost,
fmt.Sprintf("%s/app/rest/builds/id:%d", config.URL, build),
strings.NewReader("<buildCancelRequest comment='build cancelled by api' readdIntoQueue='false' />"),
)
if err != nil {
return err
}

req.Header.Add("Content-Type", "application/xml")
req.Header.Add("Accept", "application/json")
req.SetBasicAuth(config.UserName, config.Password)

client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()

if res.StatusCode != 200 {
body, _ := ioutil.ReadAll(res.Body)
return fmt.Errorf("error making request: %s", string(body))
}
return nil
}

// LastBuild ...
func LastBuild(config config.Config, build string) (*Build, error) {
req, err := http.NewRequest(
Expand Down

0 comments on commit 3e67276

Please sign in to comment.