gojenkins

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2025 License: Apache-2.0 Imports: 21 Imported by: 163

README

Jenkins API Client for Go

GoDoc Go Report Cart 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
  • Create and Delete Users
  • Get Current Queue, Cancel Tasks
  • Create and Revoke API Tokens
  • etc. For all methods go to GoDoc Reference.

Installation

go get github.com/bndr/gojenkins

CLI

For users that would like CLI based on gojenkins, follow the steps below:

$ cd cli/jenkinsctl
$ make

Usage


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(ctx)


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

job, err := jenkins.GetJob(ctx, "#jobname")
if err != nil {
  panic(err)
}
queueid, err := job.InvokeSimple(ctx, params) // or  jenkins.BuildJob(ctx, "#jobname", params)
if err != nil {
  panic(err)
}
build, err := jenkins.GetBuildFromQueueID(ctx, job, queueid)
if err != nil {
  panic(err)
}

// Wait for build to finish
for build.IsRunning(ctx) {
  time.Sleep(5000 * time.Millisecond)
  build.Poll(ctx)
}

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

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(nil, "http://localhost:8080/", "admin", "admin").Init(ctx)

or if you don't need authentication:

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

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

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

By default, gojenkins will use the http.DefaultClient if none is passed into the CreateJenkins() function.

Check Status of all nodes
nodes := jenkins.GetAllNodes(ctx)

for _, node := range nodes {

  // Fetch Node Data
  node.Poll(ctx)
	if node.IsOnline(ctx) {
		fmt.Println("Node is Online")
	}
}

Get all Builds for specific Job, and check their status
jobName := "someJob"
builds, err := jenkins.GetAllBuildIds(ctx, jobName)

if err != nil {
  panic(err)
}

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

  if err != nil {
    panic(err)
  }

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

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

if err != nil {
  panic(err)
}

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

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

tasks := jenkins.GetQueue(ctx)

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

Create View and add Jobs to it

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

if err != nil {
  panic(err)
}

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

if status != nil {
  fmt.Println("Job has been added to view")
}

Create nested Folders and create Jobs in them

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

// Create child folder in parent folder
cFolder, err := jenkins.CreateFolder(ctx, "childFolder", pFolder.GetName())
if err != nil {
  panic(err)
}

// Create job in child folder
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>`

job, err := jenkins.CreateJobInFolder(ctx, configString, "jobInFolder", pFolder.GetName(), cFolder.GetName())
if err != nil {
  panic(err)
}

if job != nil {
	fmt.Println("Job has been created in child folder")
}

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

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

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

To always get fresh data use the .Poll() method

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

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

Create and Delete Users
// Create user
user, err := jenkins.CreateUser(ctx, "username", "password", "fullname", "user@email.com")
if err != nil {
  log.Fatal(err)
}
// Delete User
err = user.Delete()
if err != nil {
  log.Fatal(err)
}
// Delete user not created by gojenkins
err = jenkins.DeleteUser("username")

Create and Revoke API Tokens

// Create a token for admin user
token, err := jenkins.GenerateAPIToken(ctx, "TestToken")
if err != nil {
  log.Fatal(err)
}

// Set Jenkins client to use new API token
jenkins.Requester.BasicAuth.Password = token.Value

// Revoke token that was just created
token.Revoke()

// Revoke all tokens for admin user
err = jenkins.RevokeAllAPITokens(ctx)
if err != nil {
  log.Fatal(err)
}

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
  • 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/([^/]*)/?"
)
View Source
const ClassUsernameCredentials = "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"

ClassUsernameCredentials is name if java class which implements credentials that store username-password pair

View Source
const KeySourceDirectEntryType = "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource"

KeySourceDirectEntryType is used when secret in provided directly as private key value

View Source
const KeySourceOnMasterType = "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$FileOnMasterPrivateKeySource"

KeySourceOnMasterType is used when private key value is path to file on jenkins master

Variables

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

Loggers

View Source
var (
	LIST_VIEW      = "hudson.model.ListView"
	NESTED_VIEW    = "hudson.plugins.nested_view.NestedView"
	MY_VIEW        = "hudson.model.MyView"
	DASHBOARD_VIEW = "hudson.plugins.view.dashboard.Dashboard"
	PIPELINE_VIEW  = "au.com.centrumsystems.hudson.plugin.buildpipeline.BuildPipelineView"
)

View type constants for creating different types of views.

Functions

This section is empty.

Types

type APIRequest added in v1.0.1

type APIRequest struct {
	Method   string
	Endpoint string
	Payload  io.Reader
	Headers  http.Header
	Suffix   string
}

APIRequest represents an HTTP request to the Jenkins API.

func NewAPIRequest added in v1.0.1

func NewAPIRequest(method string, endpoint string, payload io.Reader) *APIRequest

NewAPIRequest creates a new API request with the specified method, endpoint, and payload.

func (*APIRequest) SetHeader added in v1.0.1

func (ar *APIRequest) SetHeader(key string, value string) *APIRequest

SetHeader sets a header on the API request.

type APIToken added in v1.2.0

type APIToken struct {
	Jenkins *Jenkins
	Name    string `json:"tokenName"`
	UUID    string `json:"tokenUuid"`
	Value   string `json:"tokenValue"`
}

APIToken is a Jenkins API token to be created for the user instantiated with the Jenkins client

func (*APIToken) Revoke added in v1.2.0

func (a *APIToken) Revoke() error

Revoke revokes the API token.

type APITokenGenerateResponse added in v1.2.0

type APITokenGenerateResponse struct {
	Status string   `json:"status"`
	Data   APIToken `json:"data"`
}

APITokenGenerateResponse is the response given by Jenkins when an API token is created

type Artifact

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

Represents an Artifact

func (Artifact) GetData

func (a Artifact) GetData(ctx context.Context) ([]byte, error)

Get raw byte data of Artifact

func (Artifact) Save

func (a Artifact) Save(ctx context.Context, path string) (bool, error)

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

func (Artifact) SaveToDir

func (a Artifact) SaveToDir(ctx context.Context, dir string) (bool, error)

Save Artifact to directory using Artifact filename.

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

Basic Authentication

type Build

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

Build represents a Jenkins build and provides methods to interact with it.

func (*Build) GetActions

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

GetActions returns all actions associated with the build.

func (*Build) GetAllFingerPrints added in v1.0.1

func (b *Build) GetAllFingerPrints(ctx context.Context) []*FingerPrint

GetAllFingerPrints returns all fingerprints associated with this build.

func (*Build) GetArtifacts

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

GetArtifacts returns all artifacts produced by the build.

func (*Build) GetBuildNumber

func (b *Build) GetBuildNumber() int64

GetBuildNumber returns the build number.

func (*Build) GetCauses

func (b *Build) GetCauses(ctx context.Context) ([]map[string]interface{}, error)

GetCauses returns the causes that triggered the build.

func (*Build) GetConsoleOutput

func (b *Build) GetConsoleOutput(ctx context.Context) string

GetConsoleOutput returns the complete console output of the build.

func (*Build) GetConsoleOutputFromIndex added in v1.0.1

func (b *Build) GetConsoleOutputFromIndex(ctx context.Context, startID int64) (consoleResponse, error)

GetConsoleOutputFromIndex returns console output starting from a specific byte offset. Useful for streaming logs progressively.

func (*Build) GetCulprits

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

GetCulprits returns the list of users who may have caused the build to fail.

func (*Build) GetDownstreamBuilds

func (b *Build) GetDownstreamBuilds(ctx context.Context) ([]*Build, error)

GetDownstreamBuilds returns all downstream builds triggered by this build.

func (*Build) GetDownstreamJobNames

func (b *Build) GetDownstreamJobNames(ctx context.Context) []string

GetDownstreamJobNames returns the names of downstream jobs that used artifacts from this build.

func (*Build) GetDuration

func (b *Build) GetDuration() float64

GetDuration returns the duration of the build in milliseconds.

func (*Build) GetInjectedEnvVars added in v1.0.1

func (b *Build) GetInjectedEnvVars(ctx context.Context) (map[string]string, error)

GetInjectedEnvVars returns the environment variables injected into the build.

func (*Build) GetMatrixRuns

func (b *Build) GetMatrixRuns(ctx context.Context) ([]*Build, error)

GetMatrixRuns returns all matrix configuration builds for a matrix project build.

func (*Build) GetParameters

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

GetParameters returns the parameters used to trigger the build.

func (*Build) GetResult

func (b *Build) GetResult() string

GetResult returns the result status of the build (e.g., SUCCESS, FAILURE).

func (*Build) GetResultSet

func (b *Build) GetResultSet(ctx context.Context) (*TestResult, error)

GetResultSet returns the test results for the build.

func (*Build) GetRevision

func (b *Build) GetRevision() string

GetRevision returns the VCS revision (commit hash) associated with the build.

func (*Build) GetRevisionBranch added in v1.0.1

func (b *Build) GetRevisionBranch() (string, error)

GetRevisionBranch returns the git branch SHA1 for the build.

func (*Build) GetTimestamp

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

GetTimestamp returns the time when the build started.

func (*Build) GetUpstreamBuild

func (b *Build) GetUpstreamBuild(ctx context.Context) (*Build, error)

GetUpstreamBuild returns the upstream build that triggered this build.

func (*Build) GetUpstreamBuildNumber

func (b *Build) GetUpstreamBuildNumber(ctx context.Context) (int64, error)

GetUpstreamBuildNumber returns the build number of the upstream build that triggered this build.

func (*Build) GetUpstreamJob

func (b *Build) GetUpstreamJob(ctx context.Context) (*Job, error)

GetUpstreamJob returns the job that triggered this build.

func (*Build) GetUrl

func (b *Build) GetUrl() string

GetUrl returns the URL of the build.

func (*Build) Info

func (b *Build) Info() *BuildResponse

Info returns the raw BuildResponse containing all build details.

func (*Build) IsGood

func (b *Build) IsGood(ctx context.Context) bool

IsGood returns true if the build completed successfully.

func (*Build) IsRunning

func (b *Build) IsRunning(ctx context.Context) bool

IsRunning returns true if the build is currently in progress.

func (*Build) Poll

func (b *Build) Poll(ctx context.Context, options ...interface{}) (int, error)

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

func (*Build) SetDescription added in v1.0.1

func (b *Build) SetDescription(ctx context.Context, description string) error

SetDescription sets the description for the build.

func (*Build) Stop

func (b *Build) Stop(ctx context.Context) (bool, error)

Stop aborts a running build.

type BuildResponse added in v1.0.1

type BuildResponse struct {
	Actions   []generalObj
	Artifacts []struct {
		DisplayPath  string `json:"displayPath"`
		FileName     string `json:"fileName"`
		RelativePath string `json:"relativePath"`
	} `json:"artifacts"`
	Building  bool   `json:"building"`
	BuiltOn   string `json:"builtOn"`
	ChangeSet struct {
		Items []struct {
			AffectedPaths []string `json:"affectedPaths"`
			Author        struct {
				AbsoluteUrl string `json:"absoluteUrl"`
				FullName    string `json:"fullName"`
			} `json:"author"`
			Comment  string `json:"comment"`
			CommitID string `json:"commitId"`
			Date     string `json:"date"`
			ID       string `json:"id"`
			Msg      string `json:"msg"`
			Paths    []struct {
				EditType string `json:"editType"`
				File     string `json:"file"`
			} `json:"paths"`
			Timestamp int64 `json:"timestamp"`
		} `json:"items"`
		Kind      string `json:"kind"`
		Revisions []struct {
			Module   string
			Revision int
		} `json:"revision"`
	} `json:"changeSet"`
	ChangeSets []struct {
		Items []struct {
			AffectedPaths []string `json:"affectedPaths"`
			Author        struct {
				AbsoluteUrl string `json:"absoluteUrl"`
				FullName    string `json:"fullName"`
			} `json:"author"`
			Comment  string `json:"comment"`
			CommitID string `json:"commitId"`
			Date     string `json:"date"`
			ID       string `json:"id"`
			Msg      string `json:"msg"`
			Paths    []struct {
				EditType string `json:"editType"`
				File     string `json:"file"`
			} `json:"paths"`
			Timestamp int64 `json:"timestamp"`
		} `json:"items"`
		Kind      string `json:"kind"`
		Revisions []struct {
			Module   string
			Revision int
		} `json:"revision"`
	} `json:"changeSets"`
	Culprits          []Culprit   `json:"culprits"`
	Description       interface{} `json:"description"`
	Duration          float64     `json:"duration"`
	EstimatedDuration float64     `json:"estimatedDuration"`
	Executor          interface{} `json:"executor"`
	DisplayName       string      `json:"displayName"`
	FullDisplayName   string      `json:"fullDisplayName"`
	ID                string      `json:"id"`
	KeepLog           bool        `json:"keepLog"`
	Number            int64       `json:"number"`
	QueueID           int64       `json:"queueId"`
	Result            string      `json:"result"`
	Timestamp         int64       `json:"timestamp"`
	URL               string      `json:"url"`
	MavenArtifacts    interface{} `json:"mavenArtifacts"`
	MavenVersionUsed  string      `json:"mavenVersionUsed"`
	FingerPrint       []FingerPrintResponse
	Runs              []struct {
		Number int64
		URL    string
	} `json:"runs"`
}

BuildResponse represents the JSON response from the Jenkins API for a build.

type BuildRevision

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

BuildRevision represents a VCS revision associated with a build.

type Builds

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

Builds represents build information for branches in a multi-branch project.

type Computers

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

Computers represents a collection of Jenkins nodes (agents).

type CredentialsManager added in v1.0.1

type CredentialsManager struct {
	J      *Jenkins
	Folder string
}

CredentialsManager is utility to control credential plugin Credentials declared by it can be used in jenkins jobs

func (CredentialsManager) Add added in v1.0.1

func (cm CredentialsManager) Add(ctx context.Context, domain string, creds interface{}) error

Add creates a new credential in the specified domain. The creds parameter must be a struct that can be marshaled to XML.

func (CredentialsManager) Delete added in v1.0.1

func (cm CredentialsManager) Delete(ctx context.Context, domain string, id string) error

Delete removes a credential from the specified domain.

func (CredentialsManager) GetSingle added in v1.0.1

func (cm CredentialsManager) GetSingle(ctx context.Context, domain string, id string, creds interface{}) error

GetSingle retrieves a single credential by domain and ID. The credential is parsed as XML into the creds parameter (must be a pointer to struct).

func (CredentialsManager) List added in v1.0.1

func (cm CredentialsManager) List(ctx context.Context, domain string) ([]string, error)

List returns the IDs of all credentials stored in the specified domain.

func (CredentialsManager) Update added in v1.0.1

func (cm CredentialsManager) Update(ctx context.Context, domain string, id string, creds interface{}) error

Update modifies an existing credential in the specified domain. The creds parameter must be a pointer to struct that can be marshaled to XML.

type Culprit

type Culprit struct {
	AbsoluteUrl string
	FullName    string
}

Culprit represents a user who may have caused a build to fail.

type DockerServerCredentials added in v1.0.1

type DockerServerCredentials struct {
	XMLName             xml.Name `xml:"org.jenkinsci.plugins.docker.commons.credentials.DockerServerCredentials"`
	ID                  string   `xml:"id"`
	Scope               string   `xml:"scope"`
	Username            string   `xml:"username"`
	Description         string   `xml:"description,omitempty"`
	ClientKey           string   `xml:"clientKey"`
	ClientCertificate   string   `xml:"clientCertificate"`
	ServerCaCertificate string   `xml:"serverCaCertificate"`
}

DockerServerCredentials represents credentials for Docker server keys.

type ErrAPIToken added in v1.2.0

type ErrAPIToken struct {
	Message string
}

ErrAPIToken occurs when there is error creating or revoking API tokens

func (*ErrAPIToken) Error added in v1.2.0

func (e *ErrAPIToken) Error() string

type ErrUser added in v1.2.0

type ErrUser struct {
	Message string
}

ErrUser occurs when there is error creating or revoking Jenkins users

func (*ErrUser) Error added in v1.2.0

func (e *ErrUser) Error() string

type Executor

type Executor struct {
	Raw     *ExecutorResponse
	Jenkins *Jenkins
}

Executor represents the Jenkins master executor information.

type ExecutorResponse added in v1.0.1

type ExecutorResponse struct {
	AssignedLabels  []map[string]string `json:"assignedLabels"`
	Description     interface{}         `json:"description"`
	Jobs            []InnerJob          `json:"jobs"`
	Mode            string              `json:"mode"`
	NodeDescription string              `json:"nodeDescription"`
	NodeName        string              `json:"nodeName"`
	NumExecutors    int64               `json:"numExecutors"`
	OverallLoad     struct{}            `json:"overallLoad"`
	PrimaryView     struct {
		Name string `json:"name"`
		URL  string `json:"url"`
	} `json:"primaryView"`
	QuietingDown   bool       `json:"quietingDown"`
	SlaveAgentPort int64      `json:"slaveAgentPort"`
	UnlabeledLoad  struct{}   `json:"unlabeledLoad"`
	UseCrumbs      bool       `json:"useCrumbs"`
	UseSecurity    bool       `json:"useSecurity"`
	Views          []ViewData `json:"views"`
}

ExecutorResponse represents the JSON response from the Jenkins API for the master executor.

type FileCredentials added in v1.2.0

type FileCredentials struct {
	XMLName     xml.Name `xml:"org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl"`
	ID          string   `xml:"id"`
	Scope       string   `xml:"scope"`
	Description string   `xml:"description"`
	Filename    string   `xml:"fileName"`
	SecretBytes string   `xml:"secretBytes"`
}

FileCredentials represents credentials that store a file. SecretBytes is a base64 encoded file content.

type FingerPrint added in v1.0.1

type FingerPrint struct {
	Jenkins *Jenkins
	Base    string
	Id      string
	Raw     *FingerPrintResponse
}

FingerPrint represents a Jenkins fingerprint used to track file usage across builds.

func (FingerPrint) GetInfo added in v1.0.1

GetInfo returns the fingerprint details.

func (FingerPrint) Poll added in v1.0.1

func (f FingerPrint) Poll(ctx context.Context) (int, error)

Poll fetches the latest fingerprint data from Jenkins.

func (FingerPrint) Valid added in v1.0.1

func (f FingerPrint) Valid(ctx context.Context) (bool, error)

Valid returns true if the fingerprint exists and matches the expected hash.

func (FingerPrint) ValidateForBuild added in v1.0.1

func (f FingerPrint) ValidateForBuild(ctx context.Context, filename string, build *Build) (bool, error)

ValidateForBuild validates the fingerprint against a specific build and filename.

type FingerPrintResponse added in v1.0.1

type FingerPrintResponse struct {
	FileName string `json:"fileName"`
	Hash     string `json:"hash"`
	Original struct {
		Name   string
		Number int64
	} `json:"original"`
	Timestamp int64 `json:"timestamp"`
	Usage     []struct {
		Name   string `json:"name"`
		Ranges struct {
			Ranges []struct {
				End   int64 `json:"end"`
				Start int64 `json:"start"`
			} `json:"ranges"`
		} `json:"ranges"`
	} `json:"usage"`
}

FingerPrintResponse represents the JSON response from the Jenkins API for a fingerprint.

type Folder added in v1.0.1

type Folder struct {
	Raw     *FolderResponse
	Jenkins *Jenkins
	Base    string
}

Folder represents a Jenkins folder that can contain jobs and other folders.

func (*Folder) Create added in v1.0.1

func (f *Folder) Create(ctx context.Context, name string) (*Folder, error)

Create creates a new folder with the given name.

func (*Folder) GetName added in v1.0.1

func (f *Folder) GetName() string

GetName returns the name of the folder.

func (*Folder) Poll added in v1.0.1

func (f *Folder) Poll(ctx context.Context) (int, error)

Poll fetches the latest folder data from Jenkins.

type FolderResponse added in v1.0.1

type FolderResponse struct {
	Actions     []generalObj
	Description string     `json:"description"`
	DisplayName string     `json:"displayName"`
	Name        string     `json:"name"`
	URL         string     `json:"url"`
	Jobs        []InnerJob `json:"jobs"`
	PrimaryView *ViewData  `json:"primaryView"`
	Views       []ViewData `json:"views"`
}

FolderResponse represents the JSON response from the Jenkins API for a folder.

type History added in v1.0.1

type History struct {
	BuildDisplayName string
	BuildNumber      int
	BuildStatus      string
	BuildTimestamp   int64
}

History represents a build history entry with status and timestamp information.

type InnerJob added in v1.0.1

type InnerJob struct {
	Class string `json:"_class"`
	Name  string `json:"name"`
	Url   string `json:"url"`
	Color string `json:"color"`
}

InnerJob represents a nested job within a folder or multibranch pipeline.

type Jenkins

type Jenkins struct {
	Server    string
	Version   string
	Raw       *ExecutorResponse
	Requester JenkinsRequester
}

func CreateJenkins

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

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

func (*Jenkins) BuildJob

func (j *Jenkins) BuildJob(ctx context.Context, name string, params map[string]string) (int64, error)

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

func (*Jenkins) CopyJob

func (j *Jenkins) CopyJob(ctx context.Context, copyFrom string, newName string) (*Job, error)

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

func (*Jenkins) CreateFolder added in v1.0.1

func (j *Jenkins) CreateFolder(ctx context.Context, name string, parents ...string) (*Folder, error)

Create a new folder This folder can be nested in other parent folders Example: jenkins.CreateFolder("newFolder", "grandparentFolder", "parentFolder")

func (*Jenkins) CreateJob

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

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) CreateJobInFolder added in v1.0.1

func (j *Jenkins) CreateJobInFolder(ctx context.Context, config string, jobName string, parentIDs ...string) (*Job, error)

Create a new job in the folder Example: jenkins.CreateJobInFolder("<config></config>", "newJobName", "myFolder", "parentFolder")

func (*Jenkins) CreateNode

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

Create a new Node Can be JNLPLauncher or SSHLauncher Example : jenkins.CreateNode("nodeName", 1, "Description", "/var/lib/jenkins", "jdk8 docker", map[string]string{"method": "JNLPLauncher"}) By Default JNLPLauncher is created Multiple labels should be separated by blanks

func (*Jenkins) CreateUser added in v1.2.0

func (j *Jenkins) CreateUser(ctx context.Context, userName, password, fullName, email string) (User, error)

CreateUser creates a new Jenkins account

func (*Jenkins) CreateView added in v0.2.0

func (j *Jenkins) CreateView(ctx context.Context, name string, viewType string) (*View, error)

Create View First Parameter - name of the View Second parameter - Type Possible Types:

gojenkins.LIST_VIEW
gojenkins.NESTED_VIEW
gojenkins.MY_VIEW
gojenkins.DASHBOARD_VIEW
gojenkins.PIPELINE_VIEW

Example: jenkins.CreateView("newView",gojenkins.LIST_VIEW)

func (*Jenkins) DeleteJob

func (j *Jenkins) DeleteJob(ctx context.Context, name string) (bool, error)

Delete a job.

func (*Jenkins) DeleteNode added in v1.0.1

func (j *Jenkins) DeleteNode(ctx context.Context, name string) (bool, error)

Delete a Jenkins slave node

func (*Jenkins) DeleteUser added in v1.2.0

func (j *Jenkins) DeleteUser(ctx context.Context, userName string) error

DeleteUser deletes a Jenkins account

func (*Jenkins) GenerateAPIToken added in v1.2.0

func (j *Jenkins) GenerateAPIToken(ctx context.Context, tokenName string) (APIToken, error)

GenerateAPIToken creates a new API token for the Jenkins client user

func (*Jenkins) GetAllBuildIds added in v0.2.0

func (j *Jenkins) GetAllBuildIds(ctx context.Context, job string) ([]JobBuild, error)

Get all builds Numbers and URLS for a specific job. There are only build IDs here, To get all the other info of the build use jenkins.GetBuild(job,buildNumber) or job.GetBuild(buildNumber)

func (*Jenkins) GetAllJobNames added in v1.0.1

func (j *Jenkins) GetAllJobNames(ctx context.Context) ([]InnerJob, error)

Get Only Array of Job Names, Color, URL Does not query each single Job.

func (*Jenkins) GetAllJobs

func (j *Jenkins) GetAllJobs(ctx context.Context) ([]*Job, error)

Get All Possible Job Objects. Each job will be queried.

func (*Jenkins) GetAllNodes

func (j *Jenkins) GetAllNodes(ctx context.Context) ([]*Node, error)

GetAllNodes retrieves all nodes (agents) in Jenkins.

func (*Jenkins) GetAllViews added in v0.2.0

func (j *Jenkins) GetAllViews(ctx context.Context) ([]*View, error)

GetAllViews retrieves all views in Jenkins.

func (*Jenkins) GetArtifactData

func (j *Jenkins) GetArtifactData(ctx context.Context, id string) (*FingerPrintResponse, error)

Get Artifact data by Hash

func (*Jenkins) GetBuild

func (j *Jenkins) GetBuild(ctx context.Context, jobName string, number int64) (*Build, error)

GetBuild retrieves a specific build by job name and build number.

func (*Jenkins) GetBuildFromQueueID added in v1.1.0

func (j *Jenkins) GetBuildFromQueueID(ctx context.Context, job *Job, queueid int64) (*Build, error)

A task in queue will be assigned a build number in a job after a few seconds. this function will return the build object.

func (*Jenkins) GetFolder added in v1.0.1

func (j *Jenkins) GetFolder(ctx context.Context, id string, parents ...string) (*Folder, error)

GetFolder retrieves a folder by its ID. Parent folder IDs can be provided for nested folders.

func (*Jenkins) GetJob

func (j *Jenkins) GetJob(ctx context.Context, id string, parentIDs ...string) (*Job, error)

GetJob retrieves a job by its ID. Parent IDs can be provided for nested jobs.

func (*Jenkins) GetJobObj added in v1.2.0

func (j *Jenkins) GetJobObj(ctx context.Context, name string) *Job

Get a job object

func (*Jenkins) GetLabel added in v1.0.1

func (j *Jenkins) GetLabel(ctx context.Context, name string) (*Label, error)

GetLabel retrieves a label by its name.

func (*Jenkins) GetNode

func (j *Jenkins) GetNode(ctx context.Context, name string) (*Node, error)

GetNode retrieves a node (agent) by its name.

func (*Jenkins) GetPlugins

func (j *Jenkins) GetPlugins(ctx context.Context, depth int) (*Plugins, error)

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(ctx context.Context) (*Queue, error)

Returns a Queue

func (*Jenkins) GetQueueItem added in v1.0.1

func (j *Jenkins) GetQueueItem(ctx context.Context, id int64) (*Task, error)

GetQueueItem returns a single queue Task

func (*Jenkins) GetQueueUrl

func (j *Jenkins) GetQueueUrl() string

func (*Jenkins) GetSubJob added in v1.0.1

func (j *Jenkins) GetSubJob(ctx context.Context, parentId string, childId string) (*Job, error)

GetSubJob retrieves a nested job within a parent job or folder.

func (*Jenkins) GetView added in v0.2.0

func (j *Jenkins) GetView(ctx context.Context, name string) (*View, error)

GetView retrieves a view by its name.

func (*Jenkins) HasPlugin

func (j *Jenkins) HasPlugin(ctx context.Context, name string) (*Plugin, error)

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(ctx context.Context) (*ExecutorResponse, error)

Get Basic Information About Jenkins

func (*Jenkins) Init

func (j *Jenkins) Init(ctx context.Context) (*Jenkins, error)

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

func (*Jenkins) InstallPlugin added in v1.0.1

func (j *Jenkins) InstallPlugin(ctx context.Context, name string, version string) error

InstallPlugin with given version and name

func (*Jenkins) Poll added in v0.2.0

func (j *Jenkins) Poll(ctx context.Context) (int, error)

Poll fetches the latest Jenkins data.

func (*Jenkins) RenameJob

func (j *Jenkins) RenameJob(ctx context.Context, job string, name string) *Job

RenameJob renames a job. First parameter job old name, second parameter job new name.

func (*Jenkins) RevokeAPIToken added in v1.2.0

func (j *Jenkins) RevokeAPIToken(ctx context.Context, tokenUuid string) error

RevokeAPIToken revokes an API token

func (*Jenkins) RevokeAllAPITokens added in v1.2.0

func (j *Jenkins) RevokeAllAPITokens(ctx context.Context) error

RevokeAllAPITokens revokes all API tokens for the Jenkins client user

func (*Jenkins) SafeRestart added in v1.0.1

func (j *Jenkins) SafeRestart(ctx context.Context) error

SafeRestart jenkins, restart will be done when there are no jobs running

func (*Jenkins) UninstallPlugin added in v1.0.1

func (j *Jenkins) UninstallPlugin(ctx context.Context, name string) error

UninstallPlugin plugin otherwise returns error

func (*Jenkins) UpdateJob added in v1.1.0

func (j *Jenkins) UpdateJob(ctx context.Context, job string, config string) *Job

UpdateJob updates an existing job's configuration. If a job exists, update its config.

func (*Jenkins) ValidateFingerPrint

func (j *Jenkins) ValidateFingerPrint(ctx context.Context, id string) (bool, error)

Verify FingerPrint

type JenkinsRequester added in v1.2.0

type JenkinsRequester interface {
	GetJSON(ctx context.Context, endpoint string, response interface{}, query map[string]string) (*http.Response, error)
	Post(ctx context.Context, endpoint string, payload io.Reader, response interface{}, query map[string]string) (*http.Response, error)
	PostXML(ctx context.Context, endpoint string, xml string, response interface{}, query map[string]string) (*http.Response, error)
	PostJSON(ctx context.Context, endpoint string, payload io.Reader, response interface{}, query map[string]string) (*http.Response, error)
	PostFiles(ctx context.Context, endpoint string, payload io.Reader, response interface{}, query map[string]string, files []string) (*http.Response, error)
	Get(ctx context.Context, endpoint string, response interface{}, query map[string]string) (*http.Response, error)
	GetXML(ctx context.Context, endpoint string, response interface{}, query map[string]string) (*http.Response, error)
}

JenkinsRequester defines the interface for making Jenkins API requests. This interface enables mocking for unit tests.

type Job

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

Job represents a Jenkins job and provides methods to interact with it.

func (*Job) Copy

func (j *Job) Copy(ctx context.Context, destinationName string) (*Job, error)

Copy creates a copy of the job with the specified destination name.

func (*Job) Create

func (j *Job) Create(ctx context.Context, config string, qr ...interface{}) (*Job, error)

Create creates a new job with the given XML configuration. Optional query parameters can be passed as the third argument.

func (*Job) Delete

func (j *Job) Delete(ctx context.Context) (bool, error)

Delete removes the job from Jenkins.

func (*Job) Disable

func (j *Job) Disable(ctx context.Context) (bool, error)

Disable disables the job, preventing it from being triggered.

func (*Job) Enable

func (j *Job) Enable(ctx context.Context) (bool, error)

Enable enables a disabled job so it can be triggered.

func (*Job) GetAllBuildIds added in v0.2.0

func (j *Job) GetAllBuildIds(ctx context.Context) ([]JobBuild, error)

Returns All Builds with Number and URL

func (*Job) GetBuild

func (j *Job) GetBuild(ctx context.Context, id int64) (*Build, error)

GetBuild retrieves a specific build by its build number.

func (*Job) GetBuildsFields added in v1.1.0

func (j *Job) GetBuildsFields(ctx context.Context, fields []string, custom interface{}) error

GetBuildsFields retrieves specific fields from the last 100 builds into a custom struct. The fields parameter specifies which build properties to fetch.

func (*Job) GetConfig

func (j *Job) GetConfig(ctx context.Context) (string, error)

GetConfig retrieves the job's XML configuration.

func (*Job) GetDescription

func (j *Job) GetDescription() string

GetDescription returns the description of the job.

func (*Job) GetDetails

func (j *Job) GetDetails() *JobResponse

GetDetails returns the raw JobResponse containing all job details.

func (*Job) GetDownstreamJobs

func (j *Job) GetDownstreamJobs(ctx context.Context) ([]*Job, error)

GetDownstreamJobs retrieves all downstream jobs with full details.

func (*Job) GetDownstreamJobsMetadata

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

GetDownstreamJobsMetadata returns metadata for all downstream jobs without fetching full details.

func (*Job) GetFirstBuild

func (j *Job) GetFirstBuild(ctx context.Context) (*Build, error)

GetFirstBuild returns the first build of the job.

func (*Job) GetInnerJob added in v1.0.1

func (j *Job) GetInnerJob(ctx context.Context, id string) (*Job, error)

GetInnerJob retrieves a specific inner job by its name.

func (*Job) GetInnerJobs added in v1.0.1

func (j *Job) GetInnerJobs(ctx context.Context) ([]*Job, error)

GetInnerJobs retrieves all inner jobs with full details.

func (*Job) GetInnerJobsMetadata added in v1.0.1

func (j *Job) GetInnerJobsMetadata() []InnerJob

GetInnerJobsMetadata returns metadata for all inner jobs (e.g., in a folder) without fetching full details.

func (*Job) GetLastBuild

func (j *Job) GetLastBuild(ctx context.Context) (*Build, error)

GetLastBuild returns the most recent build of the job.

func (*Job) GetLastCompletedBuild

func (j *Job) GetLastCompletedBuild(ctx context.Context) (*Build, error)

GetLastCompletedBuild returns the last completed build of the job (successful or failed).

func (*Job) GetLastFailedBuild

func (j *Job) GetLastFailedBuild(ctx context.Context) (*Build, error)

GetLastFailedBuild returns the last failed build of the job.

func (*Job) GetLastStableBuild

func (j *Job) GetLastStableBuild(ctx context.Context) (*Build, error)

GetLastStableBuild returns the last stable build of the job.

func (*Job) GetLastSuccessfulBuild

func (j *Job) GetLastSuccessfulBuild(ctx context.Context) (*Build, error)

GetLastSuccessfulBuild returns the last successful build of the job.

func (*Job) GetName

func (j *Job) GetName() string

GetName returns the name of the job.

func (*Job) GetParameters

func (j *Job) GetParameters(ctx context.Context) ([]ParameterDefinition, error)

GetParameters returns the parameter definitions for a parameterized job.

func (*Job) GetPipelineRun added in v1.0.1

func (job *Job) GetPipelineRun(ctx context.Context, id string) (pr *PipelineRun, err error)

GetPipelineRun returns a specific pipeline run by its ID.

func (*Job) GetPipelineRuns added in v1.0.1

func (job *Job) GetPipelineRuns(ctx context.Context) (pr []PipelineRun, err error)

GetPipelineRuns returns all pipeline runs for a pipeline job.

func (*Job) GetUpstreamJobs

func (j *Job) GetUpstreamJobs(ctx context.Context) ([]*Job, error)

GetUpstreamJobs retrieves all upstream jobs with full details.

func (*Job) GetUpstreamJobsMetadata

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

GetUpstreamJobsMetadata returns metadata for all upstream jobs without fetching full details.

func (*Job) HasQueuedBuild

func (j *Job) HasQueuedBuild(ctx context.Context) (bool, error)

HasQueuedBuild returns true if the job has a build waiting in the queue.

func (*Job) History added in v1.0.1

func (j *Job) History(ctx context.Context) ([]*History, error)

History retrieves the build history of the job.

func (*Job) Invoke

func (j *Job) Invoke(ctx context.Context, files []string, skipIfRunning bool, params map[string]string, cause string, securityToken string) (bool, error)

Invoke triggers a build with optional file parameters, build parameters, and security token. If skipIfRunning is true, the build will not be triggered if the job is already running.

func (*Job) InvokeSimple

func (j *Job) InvokeSimple(ctx context.Context, params map[string]string) (int64, error)

InvokeSimple triggers a build with the given parameters and returns the queue item number. It automatically chooses between /build and /buildWithParameters based on job configuration.

func (*Job) IsEnabled

func (j *Job) IsEnabled(ctx context.Context) (bool, error)

IsEnabled returns true if the job is enabled and can be triggered.

func (*Job) IsQueued

func (j *Job) IsQueued(ctx context.Context) (bool, error)

IsQueued returns true if the job is currently waiting in the build queue.

func (*Job) IsRunning

func (j *Job) IsRunning(ctx context.Context) (bool, error)

IsRunning returns true if the job's last build is currently running.

func (*Job) Poll

func (j *Job) Poll(ctx context.Context) (int, error)

Poll fetches the latest job data from Jenkins and updates the Raw field. Returns the HTTP status code of the response.

func (*Job) Rename

func (j *Job) Rename(ctx context.Context, name string) (bool, error)

Rename changes the name of the job.

func (*Job) UpdateConfig added in v1.0.1

func (j *Job) UpdateConfig(ctx context.Context, config string) error

UpdateConfig updates the job's XML configuration.

type JobBuild added in v1.0.1

type JobBuild struct {
	Number int64
	URL    string
}

JobBuild represents basic build information including its number and URL.

type JobResponse added in v1.0.1

type JobResponse struct {
	Class              string `json:"_class"`
	Actions            []generalObj
	Buildable          bool `json:"buildable"`
	Builds             []JobBuild
	Color              string      `json:"color"`
	ConcurrentBuild    bool        `json:"concurrentBuild"`
	Description        string      `json:"description"`
	DisplayName        string      `json:"displayName"`
	DisplayNameOrNull  interface{} `json:"displayNameOrNull"`
	DownstreamProjects []InnerJob  `json:"downstreamProjects"`
	FirstBuild         JobBuild
	FullName           string `json:"fullName"`
	FullDisplayName    string `json:"fullDisplayName"`
	HealthReport       []struct {
		Description   string `json:"description"`
		IconClassName string `json:"iconClassName"`
		IconUrl       string `json:"iconUrl"`
		Score         int64  `json:"score"`
	} `json:"healthReport"`
	InQueue               bool     `json:"inQueue"`
	KeepDependencies      bool     `json:"keepDependencies"`
	LastBuild             JobBuild `json:"lastBuild"`
	LastCompletedBuild    JobBuild `json:"lastCompletedBuild"`
	LastFailedBuild       JobBuild `json:"lastFailedBuild"`
	LastStableBuild       JobBuild `json:"lastStableBuild"`
	LastSuccessfulBuild   JobBuild `json:"lastSuccessfulBuild"`
	LastUnstableBuild     JobBuild `json:"lastUnstableBuild"`
	LastUnsuccessfulBuild JobBuild `json:"lastUnsuccessfulBuild"`
	Name                  string   `json:"name"`
	NextBuildNumber       int64    `json:"nextBuildNumber"`
	Property              []struct {
		ParameterDefinitions []ParameterDefinition `json:"parameterDefinitions"`
	} `json:"property"`
	QueueItem        interface{} `json:"queueItem"`
	Scm              struct{}    `json:"scm"`
	UpstreamProjects []InnerJob  `json:"upstreamProjects"`
	URL              string      `json:"url"`
	Jobs             []InnerJob  `json:"jobs"`
	PrimaryView      *ViewData   `json:"primaryView"`
	Views            []ViewData  `json:"views"`
}

JobResponse represents the JSON response from the Jenkins API for a job.

type Label added in v1.0.1

type Label struct {
	Raw     *LabelResponse
	Jenkins *Jenkins
	Base    string
}

Label represents a Jenkins label used to group nodes.

func (*Label) GetName added in v1.0.1

func (l *Label) GetName() string

GetName returns the name of the label.

func (*Label) GetNodes added in v1.0.1

func (l *Label) GetNodes() []LabelNode

GetNodes returns all nodes associated with the label.

func (*Label) Poll added in v1.0.1

func (l *Label) Poll(ctx context.Context) (int, error)

Poll fetches the latest label data from Jenkins.

type LabelNode added in v1.0.1

type LabelNode struct {
	NodeName        string `json:"nodeName"`
	NodeDescription string `json:"nodeDescription"`
	NumExecutors    int64  `json:"numExecutors"`
	Mode            string `json:"mode"`
	Class           string `json:"_class"`
}

LabelNode represents a node associated with a label.

type LabelResponse added in v1.0.1

type LabelResponse struct {
	Name           string      `json:"name"`
	Description    string      `json:"description"`
	Nodes          []LabelNode `json:"nodes"`
	Offline        bool        `json:"offline"`
	IdleExecutors  int64       `json:"idleExecutors"`
	BusyExecutors  int64       `json:"busyExecutors"`
	TotalExecutors int64       `json:"totalExecutors"`
}

LabelResponse represents the JSON response from the Jenkins API for a label.

type MODE added in v1.0.1

type MODE string

MODE represents the usage mode for a node.

const (
	NORMAL    MODE = "NORMAL"
	EXCLUSIVE MODE = "EXCLUSIVE"
)

Node usage mode constants.

type Node

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

Node represents a Jenkins agent (slave) node.

func (*Node) Delete

func (n *Node) Delete(ctx context.Context) (bool, error)

Delete removes the node from Jenkins.

func (*Node) Disconnect added in v1.0.1

func (n *Node) Disconnect(ctx context.Context) (int, error)

Disconnect disconnects the node from Jenkins.

func (*Node) GetLogText added in v1.0.1

func (n *Node) GetLogText(ctx context.Context) (string, error)

GetLogText returns the agent log text for the node.

func (*Node) GetName

func (n *Node) GetName() string

GetName returns the display name of the node.

func (*Node) Info

func (n *Node) Info(ctx context.Context) (*NodeResponse, error)

Info returns the node details after polling for the latest data.

func (*Node) IsIdle

func (n *Node) IsIdle(ctx context.Context) (bool, error)

IsIdle returns true if the node has no builds running.

func (*Node) IsJnlpAgent

func (n *Node) IsJnlpAgent(ctx context.Context) (bool, error)

IsJnlpAgent returns true if the node is a JNLP (Java Web Start) agent.

func (*Node) IsOnline

func (n *Node) IsOnline(ctx context.Context) (bool, error)

IsOnline returns true if the node is online and available.

func (*Node) IsTemporarilyOffline

func (n *Node) IsTemporarilyOffline(ctx context.Context) (bool, error)

IsTemporarilyOffline returns true if the node is temporarily marked offline.

func (*Node) LaunchNodeBySSH added in v1.0.1

func (n *Node) LaunchNodeBySSH(ctx context.Context) (int, error)

LaunchNodeBySSH launches the node's agent via SSH.

func (*Node) Poll

func (n *Node) Poll(ctx context.Context) (int, error)

Poll fetches the latest node data from Jenkins.

func (*Node) SetOffline

func (n *Node) SetOffline(ctx context.Context, options ...interface{}) (bool, error)

SetOffline marks the node as temporarily offline with an optional message.

func (*Node) SetOnline

func (n *Node) SetOnline(ctx context.Context) (bool, error)

SetOnline brings a temporarily offline node back online.

func (*Node) ToggleTemporarilyOffline

func (n *Node) ToggleTemporarilyOffline(ctx context.Context, options ...interface{}) (bool, error)

ToggleTemporarilyOffline toggles the temporarily offline status of the node.

type NodeResponse added in v1.0.1

type NodeResponse struct {
	Class       string        `json:"_class"`
	Actions     []interface{} `json:"actions"`
	DisplayName string        `json:"displayName"`
	Executors   []struct {
		CurrentExecutable struct {
			Number    int    `json:"number"`
			URL       string `json:"url"`
			SubBuilds []struct {
				Abort             bool        `json:"abort"`
				Build             interface{} `json:"build"`
				BuildNumber       int         `json:"buildNumber"`
				Duration          string      `json:"duration"`
				Icon              string      `json:"icon"`
				JobName           string      `json:"jobName"`
				ParentBuildNumber int         `json:"parentBuildNumber"`
				ParentJobName     string      `json:"parentJobName"`
				PhaseName         string      `json:"phaseName"`
				Result            string      `json:"result"`
				Retry             bool        `json:"retry"`
				URL               string      `json:"url"`
			} `json:"subBuilds"`
		} `json:"currentExecutable"`
	} `json:"executors"`
	Icon                string   `json:"icon"`
	IconClassName       string   `json:"iconClassName"`
	Idle                bool     `json:"idle"`
	JnlpAgent           bool     `json:"jnlpAgent"`
	LaunchSupported     bool     `json:"launchSupported"`
	LoadStatistics      struct{} `json:"loadStatistics"`
	ManualLaunchAllowed bool     `json:"manualLaunchAllowed"`
	MonitorData         struct {
		Hudson_NodeMonitors_ArchitectureMonitor interface{} `json:"hudson.node_monitors.ArchitectureMonitor"`
		Hudson_NodeMonitors_ClockMonitor        interface{} `json:"hudson.node_monitors.ClockMonitor"`
		Hudson_NodeMonitors_DiskSpaceMonitor    interface{} `json:"hudson.node_monitors.DiskSpaceMonitor"`
		Hudson_NodeMonitors_ResponseTimeMonitor struct {
			Average int64 `json:"average"`
		} `json:"hudson.node_monitors.ResponseTimeMonitor"`
		Hudson_NodeMonitors_SwapSpaceMonitor      interface{} `json:"hudson.node_monitors.SwapSpaceMonitor"`
		Hudson_NodeMonitors_TemporarySpaceMonitor interface{} `json:"hudson.node_monitors.TemporarySpaceMonitor"`
	} `json:"monitorData"`
	NumExecutors       int64         `json:"numExecutors"`
	Offline            bool          `json:"offline"`
	OfflineCause       struct{}      `json:"offlineCause"`
	OfflineCauseReason string        `json:"offlineCauseReason"`
	OneOffExecutors    []interface{} `json:"oneOffExecutors"`
	TemporarilyOffline bool          `json:"temporarilyOffline"`
}

NodeResponse represents the JSON response from the Jenkins API for a node.

type ParameterDefinition added in v1.0.1

type ParameterDefinition struct {
	DefaultParameterValue struct {
		Name  string      `json:"name"`
		Value interface{} `json:"value"`
	} `json:"defaultParameterValue"`
	Description string `json:"description"`
	Name        string `json:"name"`
	Type        string `json:"type"`
}

ParameterDefinition represents a build parameter definition for a parameterized job.

type PipelineArtifact added in v1.0.1

type PipelineArtifact struct {
	ID   string
	Name string
	Path string
	URL  string
	Size int `json:"size"`
}

PipelineArtifact represents an artifact produced by a pipeline run.

type PipelineInputAction added in v1.0.1

type PipelineInputAction struct {
	ID         string
	Message    string
	ProceedURL string
	AbortURL   string
}

PipelineInputAction represents a pending input action that requires user interaction.

type PipelineNode added in v1.0.1

type PipelineNode struct {
	Run            *PipelineRun
	Base           string
	URLs           map[string]map[string]string `json:"_links"`
	ID             string
	Name           string
	Status         string
	StartTime      int64 `json:"startTimeMillis"`
	Duration       int64 `json:"durationMillis"`
	StageFlowNodes []PipelineNode
	ParentNodes    []int64
}

PipelineNode represents a stage or step within a pipeline run.

func (*PipelineNode) GetLog added in v1.0.1

func (node *PipelineNode) GetLog(ctx context.Context) (log *PipelineNodeLog, err error)

GetLog returns the console log output for a pipeline node.

type PipelineNodeLog added in v1.0.1

type PipelineNodeLog struct {
	NodeID     string
	NodeStatus string
	Length     int64
	HasMore    bool
	Text       string
	ConsoleURL string
}

PipelineNodeLog represents the console log output for a pipeline node.

type PipelineRun added in v1.0.1

type PipelineRun struct {
	Job       *Job
	Base      string
	URLs      map[string]map[string]string `json:"_links"`
	ID        string
	Name      string
	Status    string
	StartTime int64 `json:"startTimeMillis"`
	EndTime   int64 `json:"endTimeMillis"`
	Duration  int64 `json:"durationMillis"`
	Stages    []PipelineNode
}

PipelineRun represents a single run of a Jenkins pipeline job.

func (*PipelineRun) AbortInput added in v1.0.1

func (pr *PipelineRun) AbortInput(ctx context.Context) (bool, error)

AbortInput aborts the first pending input action for a pipeline run.

func (*PipelineRun) GetArtifacts added in v1.0.1

func (pr *PipelineRun) GetArtifacts(ctx context.Context) (artifacts []PipelineArtifact, err error)

GetArtifacts returns all artifacts produced by a pipeline run.

func (*PipelineRun) GetNode added in v1.0.1

func (pr *PipelineRun) GetNode(ctx context.Context, id string) (node *PipelineNode, err error)

GetNode returns a specific pipeline node by its ID.

func (*PipelineRun) GetPendingInputActions added in v1.0.1

func (pr *PipelineRun) GetPendingInputActions(ctx context.Context) (PIAs []PipelineInputAction, err error)

GetPendingInputActions returns all pending input actions for a pipeline run.

func (*PipelineRun) ProceedInput added in v1.0.1

func (pr *PipelineRun) ProceedInput(ctx context.Context) (bool, error)

ProceedInput submits the first pending input action for a pipeline run.

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"`
}

Plugin represents a single Jenkins plugin.

type PluginResponse added in v1.0.1

type PluginResponse struct {
	Plugins []Plugin `json:"plugins"`
}

PluginResponse represents the JSON response from the Jenkins API for plugins.

type Plugins

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

Plugins represents the collection of installed Jenkins plugins.

func (*Plugins) Contains

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

Contains checks if a plugin with the given name is installed. Returns the Plugin if found, nil otherwise.

func (*Plugins) Count added in v0.2.0

func (p *Plugins) Count() int

Count returns the total number of installed plugins.

func (*Plugins) Poll

func (p *Plugins) Poll(ctx context.Context) (int, error)

Poll fetches the latest plugin data from Jenkins.

type PrivateKey added in v1.0.1

type PrivateKey struct {
	Value string `xml:"privateKey"`
	Class string `xml:"class,attr"`
}

PrivateKey is used in SSHCredentials type. Class can be either KeySourceDirectEntryType (value is the secret text) or KeySourceOnMasterType (value is the path on master where secret is stored).

type PrivateKeyFile added in v1.0.1

type PrivateKeyFile struct {
	Value string `xml:"privateKeyFile"`
	Class string `xml:"class,attr"`
}

PrivateKeyFile represents a private key stored in a file on the Jenkins master.

type Queue

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

Queue represents the Jenkins build queue.

func (*Queue) CancelTask

func (q *Queue) CancelTask(ctx context.Context, id int64) (bool, error)

CancelTask cancels a queued task by its ID.

func (*Queue) GetTaskById

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

GetTaskById returns a task from the queue by its ID.

func (*Queue) GetTasksForJob

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

GetTasksForJob returns all queued tasks for a specific job.

func (*Queue) Poll

func (q *Queue) Poll(ctx context.Context) (int, error)

Poll fetches the latest queue data from Jenkins.

func (*Queue) Tasks

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

Tasks returns all tasks currently in the queue.

type Requester

type Requester struct {
	Base      string
	BasicAuth *BasicAuth
	Client    *http.Client
	CACert    []byte
	SslVerify bool
}

Requester handles HTTP requests to the Jenkins API.

func (*Requester) Do

func (r *Requester) Do(ctx context.Context, ar *APIRequest, responseStruct interface{}, options ...interface{}) (*http.Response, error)

Do executes the API request and returns the HTTP response.

func (*Requester) Get

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

Get sends a GET request to the specified endpoint.

func (*Requester) GetJSON

func (r *Requester) GetJSON(ctx context.Context, endpoint string, responseStruct interface{}, query map[string]string) (*http.Response, error)

GetJSON sends a GET request and expects a JSON response.

func (*Requester) GetXML

func (r *Requester) GetXML(ctx context.Context, endpoint string, responseStruct interface{}, query map[string]string) (*http.Response, error)

GetXML sends a GET request and expects an XML response.

func (*Requester) Post

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

Post sends a POST request with form-urlencoded content type.

func (*Requester) PostFiles

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

PostFiles sends a POST request with file attachments.

func (*Requester) PostJSON added in v1.0.1

func (r *Requester) PostJSON(ctx context.Context, endpoint string, payload io.Reader, responseStruct interface{}, querystring map[string]string) (*http.Response, error)

PostJSON sends a POST request with JSON content type.

func (*Requester) PostXML

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

PostXML sends a POST request with XML content.

func (*Requester) ReadJSONResponse added in v1.0.1

func (r *Requester) ReadJSONResponse(response *http.Response, responseStruct interface{}) (*http.Response, error)

ReadJSONResponse reads the response body as JSON and decodes it into responseStruct.

func (*Requester) ReadRawResponse added in v1.0.1

func (r *Requester) ReadRawResponse(response *http.Response, responseStruct interface{}) (*http.Response, error)

ReadRawResponse reads the response body as a raw string.

func (*Requester) SetClient

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

SetClient sets the HTTP client to use for requests.

func (*Requester) SetCrumb added in v1.0.1

func (r *Requester) SetCrumb(ctx context.Context, ar *APIRequest) error

SetCrumb fetches and sets the CSRF crumb token on the request.

type SSHCredentials added in v1.0.1

type SSHCredentials struct {
	XMLName          xml.Name    `xml:"com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey"`
	ID               string      `xml:"id"`
	Scope            string      `xml:"scope"`
	Username         string      `xml:"username"`
	Description      string      `xml:"description,omitempty"`
	PrivateKeySource interface{} `xml:"privateKeySource"`
	Passphrase       string      `xml:"passphrase,omitempty"`
}

SSHCredentials represents credentials for SSH keys.

type StringCredentials added in v1.0.1

type StringCredentials struct {
	XMLName     xml.Name `xml:"org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl"`
	ID          string   `xml:"id"`
	Scope       string   `xml:"scope"`
	Description string   `xml:"description"`
	Secret      string   `xml:"secret"`
}

StringCredentials represents credentials that store only a secret text value.

type Task

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

Task represents a single item in the Jenkins build queue.

func (*Task) Cancel

func (t *Task) Cancel(ctx context.Context) (bool, error)

Cancel removes the task from the build queue.

func (*Task) GetCauses

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

GetCauses returns the causes that triggered this task.

func (*Task) GetJob

func (t *Task) GetJob(ctx context.Context) (*Job, error)

GetJob returns the job associated with this task.

func (*Task) GetParameters

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

GetParameters returns the build parameters for this task.

func (*Task) GetWhy

func (t *Task) GetWhy() string

GetWhy returns the reason why the task is waiting in the queue.

func (*Task) Poll added in v1.0.1

func (t *Task) Poll(ctx context.Context) (int, error)

Poll fetches the latest task data from Jenkins.

type TestResult

type TestResult struct {
	Duration  float64 `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        float64     `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  float64     `json:"duration"`
		ID        interface{} `json:"id"`
		Name      string      `json:"name"`
		Stderr    interface{} `json:"stderr"`
		Stdout    interface{} `json:"stdout"`
		Timestamp interface{} `json:"timestamp"`
	} `json:"suites"`
}

TestResult represents the test results of a build.

type User added in v1.2.0

type User struct {
	Jenkins  *Jenkins
	UserName string
	FullName string
	Email    string
}

User is a Jenkins account

func (*User) Delete added in v1.2.0

func (u *User) Delete() error

Delete removes the user's Jenkins account.

type UsernameCredentials added in v1.0.1

type UsernameCredentials struct {
	XMLName     xml.Name `xml:"com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"`
	ID          string   `xml:"id"`
	Scope       string   `xml:"scope"`
	Description string   `xml:"description"`
	Username    string   `xml:"username"`
	Password    string   `xml:"password"`
}

UsernameCredentials struct representing credential for storing username-password pair

type View added in v0.2.0

type View struct {
	Raw     *ViewResponse
	Jenkins *Jenkins
	Base    string
}

View represents a Jenkins view that organizes jobs.

func (*View) AddJob added in v0.2.0

func (v *View) AddJob(ctx context.Context, name string) (bool, error)

Returns True if successfully added Job, otherwise false

func (*View) DeleteJob added in v0.2.0

func (v *View) DeleteJob(ctx context.Context, name string) (bool, error)

Returns True if successfully deleted Job, otherwise false

func (*View) GetDescription added in v1.0.1

func (v *View) GetDescription() string

GetDescription returns the description of the view.

func (*View) GetJobs added in v1.0.1

func (v *View) GetJobs() []InnerJob

GetJobs returns all jobs in the view.

func (*View) GetName added in v1.0.1

func (v *View) GetName() string

GetName returns the name of the view.

func (*View) GetUrl added in v1.0.1

func (v *View) GetUrl() string

GetUrl returns the URL of the view.

func (*View) Poll added in v0.2.0

func (v *View) Poll(ctx context.Context) (int, error)

Poll fetches the latest view data from Jenkins.

type ViewData added in v1.0.1

type ViewData struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

ViewData represents basic view information.

type ViewResponse added in v1.0.1

type ViewResponse struct {
	Description string        `json:"description"`
	Jobs        []InnerJob    `json:"jobs"`
	Name        string        `json:"name"`
	Property    []interface{} `json:"property"`
	URL         string        `json:"url"`
}

ViewResponse represents the JSON response from the Jenkins API for a view.

Jump to

Keyboard shortcuts

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