Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add context in functions to make debugging easier and Add GetBuildFromQueueID() function #220

Merged
merged 3 commits into from
Dec 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 42 additions & 60 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,59 +26,41 @@ These are some of the features that are currently implemented:

```go

import "github.com/bndr/gojenkins"

import (
"github.com/bndr/gojenkins"
"context"
"time"
"fmt"
)

ctx := context.Background()
jenkins := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin")
// Provide CA certificate if server is using self-signed certificate
// caCert, _ := ioutil.ReadFile("/tmp/ca.crt")
// jenkins.Requester.CACert = caCert
_, err := jenkins.Init()
_, err := jenkins.Init(ctx)


if err != nil {
panic("Something Went Wrong")
}

build, err := jenkins.GetJob("job_name")
queueid, err := jenkins.BuildJob(ctx, "#jobname")
if err != nil {
panic("Job Does Not Exist")
panic(err)
}

lastSuccessBuild, err := build.GetLastSuccessfulBuild()
build, err := jenkins.GetBuildFromQueueID(ctx, queueid)
if err != nil {
panic("Last SuccessBuild does not exist")
panic(err)
}

duration := lastSuccessBuild.GetDuration()

job, err := jenkins.GetJob("jobname")

if err != nil {
panic("Job does not exist")
// Wait for build to finish
for build.IsRunning(ctx) {
time.Sleep(5000 * time.Millisecond)
build.Poll(ctx)
}

job.Rename("SomeotherJobName")

configString := `<?xml version='1.0' encoding='UTF-8'?>
<project>
<actions/>
<description></description>
<keepDependencies>false</keepDependencies>
<properties/>
<scm class="hudson.scm.NullSCM"/>
<canRoam>true</canRoam>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers class="vector"/>
<concurrentBuild>false</concurrentBuild>
<builders/>
<publishers/>
<buildWrappers/>
</project>`

j.CreateJob(configString, "someNewJobsName")

fmt.Printf("build number %d with result: %v\n", build.GetBuildNumber(), build.GetResult())

```

Expand All @@ -90,20 +72,20 @@ For all of the examples below first create a jenkins object
```go
import "github.com/bndr/gojenkins"

jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init()
jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx)
```

or if you don't need authentication:

```go
jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/").Init()
jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/").Init(ctx)
```

you can also specify your own `http.Client` (for instance, providing your own SSL configurations):

```go
client := &http.Client{ ... }
jenkins, := gojenkins.CreateJenkins(client, "http://localhost:8080/").Init()
jenkins, := gojenkins.CreateJenkins(client, "http://localhost:8080/").Init(ctx)
```

By default, `gojenkins` will use the `http.DefaultClient` if none is passed into the `CreateJenkins()`
Expand All @@ -112,13 +94,13 @@ function.
### Check Status of all nodes

```go
nodes := jenkins.GetAllNodes()
nodes := jenkins.GetAllNodes(ctx)

for _, node := range nodes {

// Fetch Node Data
node.Poll()
if node.IsOnline() {
node.Poll(ctx)
if node.IsOnline(ctx) {
fmt.Println("Node is Online")
}
}
Expand All @@ -129,45 +111,45 @@ for _, node := range nodes {

```go
jobName := "someJob"
builds, err := jenkins.GetAllBuildIds(jobName)
builds, err := jenkins.GetAllBuildIds(ctx, jobName)

if err != nil {
panic(err)
}

for _, build := range builds {
buildId := build.Number
data, err := jenkins.GetBuild(jobName, buildId)
data, err := jenkins.GetBuild(ctx, jobName, buildId)

if err != nil {
panic(err)
}

if "SUCCESS" == data.GetResult() {
if "SUCCESS" == data.GetResult(ctx) {
fmt.Println("This build succeeded")
}
}

// Get Last Successful/Failed/Stable Build for a Job
job, err := jenkins.GetJob("someJob")
job, err := jenkins.GetJob(ctx, "someJob")

if err != nil {
panic(err)
}

job.GetLastSuccessfulBuild()
job.GetLastStableBuild()
job.GetLastSuccessfulBuild(ctx)
job.GetLastStableBuild(ctx)

```

### Get Current Tasks in Queue, and the reason why they're in the queue

```go

tasks := jenkins.GetQueue()
tasks := jenkins.GetQueue(ctx)

for _, task := range tasks {
fmt.Println(task.GetWhy())
fmt.Println(task.GetWhy(ctx))
}

```
Expand All @@ -176,13 +158,13 @@ for _, task := range tasks {

```go

view, err := jenkins.CreateView("test_view", gojenkins.LIST_VIEW)
view, err := jenkins.CreateView(ctx, "test_view", gojenkins.LIST_VIEW)

if err != nil {
panic(err)
}

status, err := view.AddJob("jobName")
status, err := view.AddJob(ctx, "jobName")

if status != nil {
fmt.Println("Job has been added to view")
Expand All @@ -195,13 +177,13 @@ if status != nil {
```go

// Create parent folder
pFolder, err := jenkins.CreateFolder("parentFolder")
pFolder, err := jenkins.CreateFolder(ctx, "parentFolder")
if err != nil {
panic(err)
}

// Create child folder in parent folder
cFolder, err := jenkins.CreateFolder("childFolder", pFolder.GetName())
cFolder, err := jenkins.CreateFolder(ctx, "childFolder", pFolder.GetName())
if err != nil {
panic(err)
}
Expand All @@ -225,7 +207,7 @@ configString := `<?xml version='1.0' encoding='UTF-8'?>
<buildWrappers/>
</project>`

job, err := jenkins.CreateJobInFolder(configString, "jobInFolder", pFolder.GetName(), cFolder.GetName())
job, err := jenkins.CreateJobInFolder(ctx, configString, "jobInFolder", pFolder.GetName(), cFolder.GetName())
if err != nil {
panic(err)
}
Expand All @@ -240,9 +222,9 @@ if job != nil {

```go

job, _ := jenkins.GetJob("job")
build, _ := job.GetBuild(1)
artifacts := build.GetArtifacts()
job, _ := jenkins.GetJob(ctx, "job")
build, _ := job.GetBuild(ctx, 1)
artifacts := build.GetArtifacts(ctx)

for _, a := range artifacts {
a.SaveToDir("/tmp")
Expand All @@ -254,10 +236,10 @@ for _, a := range artifacts {

```go

job, _ := jenkins.GetJob("job")
job, _ := jenkins.GetJob(ctx, "job")
job.Poll()

build, _ := job.getBuild(1)
build, _ := job.getBuild(ctx, 1)
build.Poll()

```
Expand Down
21 changes: 11 additions & 10 deletions artifact.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package gojenkins

import (
"context"
"crypto/md5"
"errors"
"fmt"
Expand All @@ -33,9 +34,9 @@ type Artifact struct {
}

// Get raw byte data of Artifact
func (a Artifact) GetData() ([]byte, error) {
func (a Artifact) GetData(ctx context.Context) ([]byte, error) {
var data string
response, err := a.Jenkins.Requester.Get(a.Path, &data, nil)
response, err := a.Jenkins.Requester.Get(ctx, a.Path, &data, nil)

if err != nil {
return nil, err
Expand All @@ -50,19 +51,19 @@ func (a Artifact) GetData() ([]byte, error) {
}

// Save artifact to a specific path, using your own filename.
func (a Artifact) Save(path string) (bool, error) {
data, err := a.GetData()
func (a Artifact) Save(ctx context.Context, path string) (bool, error) {
data, err := a.GetData(ctx)

if err != nil {
return false, errors.New("No Data received, not saving file.")
return false, errors.New("No data received, not saving file")
}

if _, err = os.Stat(path); err == nil {
Warning.Println("Local Copy already exists, Overwriting...")
}

err = ioutil.WriteFile(path, data, 0644)
a.validateDownload(path)
a.validateDownload(ctx, path)

if err != nil {
return false, err
Expand All @@ -71,25 +72,25 @@ func (a Artifact) Save(path string) (bool, error) {
}

// Save Artifact to directory using Artifact filename.
func (a Artifact) SaveToDir(dir string) (bool, error) {
func (a Artifact) SaveToDir(ctx context.Context, dir string) (bool, error) {
if _, err := os.Stat(dir); err != nil {
Error.Printf("can't save artifact: directory %s does not exist", dir)
return false, fmt.Errorf("can't save artifact: directory %s does not exist", dir)
}
saved, err := a.Save(path.Join(dir, a.FileName))
saved, err := a.Save(ctx, path.Join(dir, a.FileName))
if err != nil {
return saved, nil
}
return saved, nil
}

// Compare Remote and local MD5
func (a Artifact) validateDownload(path string) (bool, error) {
func (a Artifact) validateDownload(ctx context.Context, path string) (bool, error) {
localHash := a.getMD5local(path)

fp := FingerPrint{Jenkins: a.Jenkins, Base: "/fingerprint/", Id: localHash, Raw: new(FingerPrintResponse)}

valid, err := fp.ValidateForBuild(a.FileName, a.Build)
valid, err := fp.ValidateForBuild(ctx, a.FileName, a.Build)

if err != nil {
return false, err
Expand Down
Loading