gojenkins

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2014 License: Apache-2.0 Imports: 20 Imported by: 0

README

Jenkins API Client for Go

GoDoc Build Status

About

Jenkins is the most popular Open Source Continuous Integration system. This Library will help you interact with Jenkins in a more developer-friendly way.

These are some of the features that are currently implemented:

  • Get information on test-results of completed/failed build
  • Ability to query Nodes, and manipulate them. Start, Stop, set Offline.
  • Ability to query Jobs, and manipulate them.
  • Get Plugins, Builds, Artifacts, Fingerprints
  • Validate Fingerprints of Artifacts
  • Get Current Queue, Cancel Tasks
  • etc. For all methods go to GoDoc Reference.

Installation

go get github.com/bndr/gojenkins

Usage


import "github.com/bndr/gojenkins"

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

build := jenkins.GetJob("job_name").GetLastSuccessfulBuild()
duration := build.GetDuration()

job := jenkins.GetJob("jobname").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")


API Reference: https://godoc.org/github.com/bndr/gojenkins

Examples

For all of the examples below first create a jenkins object

import "github.com/bndr/gojenkins"

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

or if you don't need authentication:

jenkins := gojenkins.CreateJenkins("http://localhost:8080/").Init()
Check Status of all nodes
nodes := jenkins.GetAllNodes()

for _, node := range nodes {
	if node.IsOnline() {
		fmt.Println("Node is Online")
	}
}

Get all Builds for specific Job, and check their status
builds := jenkins.GetAllBuilds("someJob",true) // If you don't preload the builds (second parameter, true = preload, false = don't preload), you will only get Build Ids

for _, build := range builds {
	if "SUCCESS" == node.GetResult() {
		fmt.Println("This build succeeded")
	}
}

// Get Last Successful/Failed/Stable Build for a Job
jenkins.GetJob("someJob").GetLastSuccessfulBuild()
jenkins.GetJob("someJob").GetLastStableBuild()

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

tasks := jenkins.GetQueue()

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

Get All Artifacts for a Build and Save them to a folder

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

for _, a := range artifacts {
	a.SaveToDir("/tmp")
}

Testing

go test

Contribute

All Contributions are welcome. The todo list is on the bottom of this README. Feel free to send a pull request.

TODO

Although the basic features are implemented there are many optional features that are on the todo list.

  • Kerberos Authentication
  • CLI Tool
  • Rewrite some (all?) iterators with channels

LICENSE

Apache License 2.0

Documentation

Overview

Gojenkins is a Jenkins Client in Go, that exposes the jenkins REST api in a more developer friendly way.

Index

Constants

View Source
const (
	STATUS_FAIL           = "FAIL"
	STATUS_ERROR          = "ERROR"
	STATUS_ABORTED        = "ABORTED"
	STATUS_REGRESSION     = "REGRESSION"
	STATUS_SUCCESS        = "SUCCESS"
	STATUS_FIXED          = "FIXED"
	STATUS_PASSED         = "PASSED"
	RESULT_STATUS_FAILURE = "FAILURE"
	RESULT_STATUS_FAILED  = "FAILED"
	RESULT_STATUS_SKIPPED = "SKIPPED"
	STR_RE_SPLIT_VIEW     = "(.*)/view/([^/]*)/?"
)

Variables

View Source
var (
	Info    *log.Logger
	Warning *log.Logger
	Error   *log.Logger
)

Loggers

Functions

This section is empty.

Types

type ActionsObject

type ActionsObject struct {
	FailCount  int64
	SkipCount  int64
	TotalCount int64
	UrlName    string
}

type Artifact

type Artifact struct {
	Jenkins  *Jenkins
	Build    *Build
	FileName string
	Path     string
}

Represents an Artifact

func (Artifact) GetData

func (a Artifact) GetData() ([]byte, error)

Get raw byte data of Artifact

func (Artifact) Save

func (a Artifact) Save(path string)

Save artifact to a specific path, using your own filename.

func (Artifact) SaveToDir

func (a Artifact) SaveToDir(dir string)

Save Artifact to directory using Artifact filename.

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

Basic Authentication

type Branch

type Branch struct {
	SHA1 string
	Name string
}

type Build

type Build struct {
	Raw     *buildResponse
	Job     *Job
	Jenkins *Jenkins
	Base    string
	Depth   int
}

func (*Build) GetActions

func (b *Build) GetActions() []GeneralObj

func (*Build) GetAllFingerprints

func (b *Build) GetAllFingerprints() []*Fingerprint

func (*Build) GetArtifacts

func (b *Build) GetArtifacts() []Artifact

func (*Build) GetBuildNumber

func (b *Build) GetBuildNumber() int

func (*Build) GetCauses

func (b *Build) GetCauses() []map[string]interface{}

func (*Build) GetConsoleOutput

func (b *Build) GetConsoleOutput() string

func (*Build) GetCulprits

func (b *Build) GetCulprits() []Culprit

func (*Build) GetDownstreamBuilds

func (b *Build) GetDownstreamBuilds() []*Build

func (*Build) GetDownstreamJobNames

func (b *Build) GetDownstreamJobNames() []string

func (*Build) GetDuration

func (b *Build) GetDuration() int

func (*Build) GetMatrixRuns

func (b *Build) GetMatrixRuns() []*Build

func (*Build) GetParameters

func (b *Build) GetParameters() []Parameter

func (*Build) GetResult

func (b *Build) GetResult() string

func (*Build) GetResultSet

func (b *Build) GetResultSet() *TestResult

func (*Build) GetRevision

func (b *Build) GetRevision() string

func (*Build) GetRevistionBranch

func (b *Build) GetRevistionBranch() string

func (*Build) GetTimestamp

func (b *Build) GetTimestamp() time.Time

func (*Build) GetUpstreamBuild

func (b *Build) GetUpstreamBuild() *Build

func (*Build) GetUpstreamBuildNumber

func (b *Build) GetUpstreamBuildNumber() int64

func (*Build) GetUpstreamJob

func (b *Build) GetUpstreamJob() *Job

func (*Build) GetUrl

func (b *Build) GetUrl() string

func (*Build) Info

func (b *Build) Info() *buildResponse

Builds

func (*Build) IsGood

func (b *Build) IsGood() bool

func (*Build) IsRunning

func (b *Build) IsRunning() bool

func (*Build) Poll

func (b *Build) Poll(options ...interface{}) int

Poll for current data. Optional parameter - depth. More about depth here: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

func (*Build) Stop

func (b *Build) Stop() bool

type BuildRevision

type BuildRevision struct {
	SHA1   string   `json:"SHA1"`
	Branch []Branch `json:"branch"`
}

type Builds

type Builds struct {
	BuildNumber int           `json:"buildNumber"`
	BuildResult interface{}   `json:"buildResult"`
	Marked      BuildRevision `json:"marked"`
	Revision    BuildRevision `json:"revision"`
}

type Computers

type Computers struct {
	BusyExecutors  int            `json:"busyExecutors"`
	Computers      []nodeResponse `json:"computer"`
	DisplayName    string         `json:"displayName"`
	TotalExecutors int            `json:"totalExecutors"`
}

type Culprit

type Culprit struct {
	AbsoluteUrl string
	FullName    string
}

type Executor

type Executor struct {
	Raw     *executorResponse
	Jenkins *Jenkins
}

type Fingerprint

type Fingerprint struct {
	Jenkins *Jenkins
	Base    string
	Id      string
	Raw     *fingerPrintResponse
}

func (Fingerprint) GetInfo

func (f Fingerprint) GetInfo() *fingerPrintResponse

func (Fingerprint) Poll

func (f Fingerprint) Poll() int

func (Fingerprint) Valid

func (f Fingerprint) Valid() bool

func (Fingerprint) ValidateForBuild

func (f Fingerprint) ValidateForBuild(filename string, build *Build) bool

type GeneralObj

type GeneralObj struct {
	Parameters              []Parameter              `json:"parameters"`
	Causes                  []map[string]interface{} `json:"causes"`
	BuildsByBranchName      map[string]Builds        `json:"buildsByBranchName"`
	LastBuiltRevision       BuildRevision            `json:"lastBuiltRevision"`
	RemoteUrls              []string                 `json:"remoteUrls"`
	ScmName                 string                   `json:"scmName"`
	MercurialNodeName       string                   `json:"mercurialNodeName"`
	MercurialRevisionNumber string                   `json:"mercurialRevisionNumber"`
	Subdir                  interface{}              `json:"subdir"`
	TotalCount              int
	UrlName                 string
}

type Jenkins

type Jenkins struct {
	Server    string
	Version   string
	Raw       *executorResponse
	Requester *Requester
}

func CreateJenkins

func CreateJenkins(base string, auth ...interface{}) *Jenkins

Creates a new Jenkins Instance Optional parameters are: username, password After creating an instance call init method.

func (*Jenkins) BuildJob

func (j *Jenkins) BuildJob(name string, options ...interface{}) bool

Invoke a job. First parameter job name, second parameter is optional Build parameters.

func (*Jenkins) CopyJob

func (j *Jenkins) CopyJob(copyFrom string, newName string) *Job

Create a copy of a job. First parameter Name of the job to copy from, Second parameter new job name.

func (*Jenkins) CreateJob

func (j *Jenkins) CreateJob(config string, options ...interface{}) *Job

Create a new job from config File Method takes XML string as first parameter, and if the name is not specified in the config file takes name as string as second parameter e.g jenkins.CreateJob("<config></config>","newJobName")

func (*Jenkins) CreateNode

func (j *Jenkins) CreateNode(name string, numExecutors int, description string, remoteFS string, options ...interface{}) *Node

Create a new Node

func (*Jenkins) DeleteJob

func (j *Jenkins) DeleteJob(name string) bool

Delete a job.

func (*Jenkins) GetAllBuilds

func (j *Jenkins) GetAllBuilds(job string, options ...interface{}) []*Build

Get all builds for a specific job. If second parameter is bool, then the Build objects will be preloaded before return e.g jenkins.GetAllBuilds("job",true) By Default preloading is turned off.

func (*Jenkins) GetAllJobs

func (j *Jenkins) GetAllJobs(preload bool) []*Job

Get All Possible jobs If preload is true, the Job object will be preloaded before returning.

func (*Jenkins) GetAllNodes

func (j *Jenkins) GetAllNodes() []*Node

func (*Jenkins) GetArtifactData

func (j *Jenkins) GetArtifactData(id string) *fingerPrintResponse

Get Artifact data by Hash

func (*Jenkins) GetBuild

func (j *Jenkins) GetBuild(job string, number string) *Build

func (*Jenkins) GetJob

func (j *Jenkins) GetJob(id string) *Job

func (*Jenkins) GetNode

func (j *Jenkins) GetNode(name string) *Node

func (*Jenkins) GetPlugins

func (j *Jenkins) GetPlugins(depth int) *Plugins

Returns the list of all plugins installed on the Jenkins server. You can supply depth parameter, to limit how much data is returned.

func (*Jenkins) GetQueue

func (j *Jenkins) GetQueue() *Queue

Returns a Queue

func (*Jenkins) GetQueueUrl

func (j *Jenkins) GetQueueUrl() string

func (*Jenkins) HasPlugin

func (j *Jenkins) HasPlugin(name string) *Plugin

Check if the plugin is installed on the server. Depth level 1 is used. If you need to go deeper, you can use GetPlugins, and iterate through them.

func (*Jenkins) Info

func (j *Jenkins) Info() *executorResponse

Get Basic Information About Jenkins

func (*Jenkins) Init

func (j *Jenkins) Init() *Jenkins

Init Method. Should be called after creating a Jenkins Instance. e.g jenkins := CreateJenkins("url").Init() HTTP Client is set here, Connection to jenkins is tested here.

func (*Jenkins) RenameJob

func (j *Jenkins) RenameJob(job string, name string) *Job

Rename a job. First parameter job old name, Second parameter job new name.

func (*Jenkins) ValidateFingerPrint

func (j *Jenkins) ValidateFingerPrint(id string) bool

Verify Fingerprint

type Job

type Job struct {
	Raw     *jobResponse
	Jenkins *Jenkins
	Base    string
}

func (*Job) Copy

func (j *Job) Copy(from string, newName string) *Job

func (*Job) Create

func (j *Job) Create(config string, qr ...interface{}) *Job

func (*Job) Delete

func (j *Job) Delete() bool

func (*Job) Disable

func (j *Job) Disable() bool

func (*Job) Enable

func (j *Job) Enable() bool

func (*Job) GetAllBuilds

func (j *Job) GetAllBuilds()

func (*Job) GetBuild

func (j *Job) GetBuild(id int64) *Build

func (*Job) GetConfig

func (j *Job) GetConfig() string

func (*Job) GetDescription

func (j *Job) GetDescription() string

func (*Job) GetDetails

func (j *Job) GetDetails() *jobResponse

func (*Job) GetDownstreamJobs

func (j *Job) GetDownstreamJobs() []*Job

func (*Job) GetDownstreamJobsMetadata

func (j *Job) GetDownstreamJobsMetadata() []updownProject

func (*Job) GetFirstBuild

func (j *Job) GetFirstBuild() *Build

func (*Job) GetLastBuild

func (j *Job) GetLastBuild() *Build

func (*Job) GetLastCompletedBuild

func (j *Job) GetLastCompletedBuild() *Build

func (*Job) GetLastFailedBuild

func (j *Job) GetLastFailedBuild() *Build

func (*Job) GetLastStableBuild

func (j *Job) GetLastStableBuild() *Build

func (*Job) GetLastSuccessfulBuild

func (j *Job) GetLastSuccessfulBuild() *Build

func (*Job) GetName

func (j *Job) GetName() string

func (*Job) GetParameters

func (j *Job) GetParameters() []parameterDefinition

func (*Job) GetUpstreamJobs

func (j *Job) GetUpstreamJobs() []*Job

func (*Job) GetUpstreamJobsMetadata

func (j *Job) GetUpstreamJobsMetadata() []updownProject

func (*Job) HasQueuedBuild

func (j *Job) HasQueuedBuild()

func (*Job) Invoke

func (j *Job) Invoke(files []string, skipIfRunning bool, params map[string]string, cause string, securityToken string) bool

func (*Job) InvokeSimple

func (j *Job) InvokeSimple(params map[string]string) bool

func (*Job) IsEnabled

func (j *Job) IsEnabled() bool

func (*Job) IsQueued

func (j *Job) IsQueued() bool

func (*Job) IsRunning

func (j *Job) IsRunning() bool

func (*Job) Poll

func (j *Job) Poll() int

func (*Job) Rename

func (j *Job) Rename(name string)

type Node

type Node struct {
	Raw     *nodeResponse
	Jenkins *Jenkins
	Base    string
}

func (*Node) Delete

func (n *Node) Delete() bool

func (*Node) GetName

func (n *Node) GetName() string

func (*Node) Info

func (n *Node) Info() *nodeResponse

func (*Node) IsIdle

func (n *Node) IsIdle() bool

func (*Node) IsJnlpAgent

func (n *Node) IsJnlpAgent() bool

func (*Node) IsOnline

func (n *Node) IsOnline() bool

func (*Node) IsTemporarilyOffline

func (n *Node) IsTemporarilyOffline() bool

func (*Node) Poll

func (n *Node) Poll() int

func (*Node) SetOffline

func (n *Node) SetOffline()

func (*Node) SetOnline

func (n *Node) SetOnline()

func (*Node) ToggleTemporarilyOffline

func (n *Node) ToggleTemporarilyOffline(options ...interface{})

type Parameter

type Parameter struct {
	Name  string
	Value string
}

type Plugin

type Plugin struct {
	Active        bool        `json:"active"`
	BackupVersion interface{} `json:"backupVersion"`
	Bundled       bool        `json:"bundled"`
	Deleted       bool        `json:"deleted"`
	Dependencies  []struct {
		Optional  string `json:"optional"`
		ShortName string `json:"shortname"`
		Version   string `json:"version"`
	} `json:"dependencies"`
	Downgradable        bool   `json:"downgradable"`
	Enabled             bool   `json:"enabled"`
	HasUpdate           bool   `json:"hasUpdate"`
	LongName            string `json:"longName"`
	Pinned              bool   `json:"pinned"`
	ShortName           string `json:"shortName"`
	SupportsDynamicLoad string `json:"supportsDynamicLoad"`
	URL                 string `json:"url"`
	Version             string `json:"version"`
}

type Plugins

type Plugins struct {
	Jenkins *Jenkins
	Raw     *pluginResponse
	Base    string
	Depth   int
}

func (*Plugins) Contains

func (p *Plugins) Contains(name string) *Plugin

func (*Plugins) Poll

func (p *Plugins) Poll() int

type Queue

type Queue struct {
	Jenkins *Jenkins
	Raw     *queueResponse
	Base    string
}

func (*Queue) CancelTask

func (q *Queue) CancelTask(id int64) bool

func (*Queue) GetTaskById

func (q *Queue) GetTaskById(id int64) *Task

func (*Queue) GetTasksForJob

func (q *Queue) GetTasksForJob(name string) []*Task

func (*Queue) Poll

func (q *Queue) Poll() int

func (*Queue) Tasks

func (q *Queue) Tasks() []*Task

type Requester

type Requester struct {
	Base         string
	BasicAuth    *BasicAuth
	Headers      http.Header
	Client       *http.Client
	SslVerify    bool
	LastResponse *http.Response
	Suffix       string
}

func (*Requester) Do

func (r *Requester) Do(method string, endpoint string, payload io.Reader, responseStruct interface{}, options ...interface{}) *http.Response

func (*Requester) Get

func (r *Requester) Get(endpoint string, responseStruct interface{}, querystring map[string]string) *http.Response

func (*Requester) GetJSON

func (r *Requester) GetJSON(endpoint string, responseStruct interface{}, querystring map[string]string) *http.Response

func (*Requester) GetXML

func (r *Requester) GetXML(endpoint string, responseStruct interface{}, querystring map[string]string) *http.Response

func (*Requester) Post

func (r *Requester) Post(endpoint string, payload io.Reader, responseStruct interface{}, querystring map[string]string) *http.Response

func (*Requester) PostFiles

func (r *Requester) PostFiles(endpoint string, payload io.Reader, responseStruct interface{}, querystring map[string]string, files []string) *http.Response

func (*Requester) PostXML

func (r *Requester) PostXML(endpoint string, xml string, responseStruct interface{}, querystring map[string]string) *http.Response

func (*Requester) SetClient

func (r *Requester) SetClient(client *http.Client) *Requester

func (*Requester) SetHeader

func (r *Requester) SetHeader(key string, value string) *Requester

type Task

type Task struct {
	Raw     *taskResponse
	Jenkins *Jenkins
	Queue   *Queue
}

func (*Task) Cancel

func (t *Task) Cancel() bool

func (*Task) GetCauses

func (t *Task) GetCauses() []map[string]interface{}

func (*Task) GetJob

func (t *Task) GetJob() *Job

func (*Task) GetParameters

func (t *Task) GetParameters() []Parameter

func (*Task) GetWhy

func (t *Task) GetWhy() string

type TestResult

type TestResult struct {
	Duration  int64 `json:"duration"`
	Empty     bool  `json:"empty"`
	FailCount int64 `json:"failCount"`
	PassCount int64 `json:"passCount"`
	SkipCount int64 `json:"skipCount"`
	Suites    []struct {
		Cases []struct {
			Age             int64       `json:"age"`
			ClassName       string      `json:"className"`
			Duration        int64       `json:"duration"`
			ErrorDetails    interface{} `json:"errorDetails"`
			ErrorStackTrace interface{} `json:"errorStackTrace"`
			FailedSince     int64       `json:"failedSince"`
			Name            string      `json:"name"`
			Skipped         bool        `json:"skipped"`
			SkippedMessage  interface{} `json:"skippedMessage"`
			Status          string      `json:"status"`
			Stderr          interface{} `json:"stderr"`
			Stdout          interface{} `json:"stdout"`
		} `json:"cases"`
		Duration  int64       `json:"duration"`
		ID        interface{} `json:"id"`
		Name      string      `json:"name"`
		Stderr    interface{} `json:"stderr"`
		Stdout    interface{} `json:"stdout"`
		Timestamp interface{} `json:"timestamp"`
	} `json:"suites"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL