gocd

package module
v0.0.0-...-c033b77 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2024 License: Apache-2.0 Imports: 7 Imported by: 1

README

Build Status GoDoc

go-gocd

Go Lang library to access GoCD API.

Usage

package main

import (
  "github.com/ashwanthkumar/go-gocd"
)

func main() {
  client := gocd.New("http://localhost:8153", "admin", "badger")
  agents, err := client.GetAllAgents()
  // ... do whatever you want with the agents
}

API Endpoints Pending

  • Agents
    • Get all Agents
    • Get one Agent
    • Update an Agent
    • Disable Agent
    • Delete an Agent
    • Agent job run history
  • Users
    • Get all Users
    • Get one user
    • Create a user
    • Update a user
    • Delete a user
  • Materials
    • Get all Materials
    • Get material modifications
    • Notify SVN materials
    • Notify git materials
  • Backups
    • Create a backup
  • Pipeline Group
    • Config listing
  • Artifacts
    • Get all Artifacts
    • Get artifact file
    • Get artifact directory
    • Create artifact
    • Append to artifact
  • Pipelines
    • Get pipeline instance
    • Get pipeline status
    • Pause a pipeline
    • Unpause a pipeline
    • Releasing a pipeline lock
    • Scheduling pipelines
    • Create a pipeline
    • Delete a pipeline
  • Stages
    • Cancel Stage
    • Get Stage instance
    • Get stage history
  • Jobs
    • Get Scheduled Jobs
    • Get Job history
  • Properties
    • Get all job Properties
    • Get one property
    • Get historical properties
    • Create property
  • Configurations
    • List all modifications
    • Get repository modification diff
    • Get Configuration
    • Create pipeline (Deprecated API)
  • Feeds (will not support)
  • Dashboard
    • Get Dashboard
  • Pipeline Config
    • Get pipeline Configuration
    • Edit Pipeline configuration
    • Create Pipeline
  • Environment Config
    • Get all environments
    • Get environment config
    • Create an environment
    • Update an environment
    • Patch an environment
    • Delete an environment

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Agent

type Agent struct {
	UUID             string    `json:"uuid,omitempty"`
	Hostname         string    `json:"hostname,omitempty"`
	IPAddress        string    `json:"ip_address,omitempty"`
	Sandbox          string    `json:"sandbox,omitempty"`
	OperatingSystem  string    `json:"operating_system,omitempty"`
	FreeSpace        FreeSpace `json:"free_space,omitempty"`
	AgentConfigState string    `json:"agent_config_state,omitempty"`
	AgentState       string    `json:"agent_state,omitempty"`
	BuildState       string    `json:"build_state,omitempty"`
	BuildDetails     struct {
		PipelineName string `json:"pipeline_name,omitempty"`
		StageName    string `json:"stage_name,omitempty"`
		JobName      string `json:"job_name,omitempty"`
	} `json:"build_details,omitempty"`
	Resources []string `json:"resources,omitempty"`
	Env       []string `json:"environments,omitempty"`
}

Agent Object

type Client

type Client interface {
	// Agents API
	GetAllAgents() ([]*Agent, error)
	GetAgent(uuid string) (*Agent, error)
	UpdateAgent(uuid string, agent *Agent) (*Agent, error)
	DisableAgent(uuid string) error
	EnableAgent(uuid string) error
	DeleteAgent(uuid string) error
	AgentRunJobHistory(uuid string, offset int) (*JobRunHistory, error)

	// Pipeline Groups API
	GetPipelineGroups() ([]*PipelineGroup, error)

	// Pipelines API
	GetPipelineInstance(string, int) (*PipelineInstance, error)
	GetPipelineHistoryPage(string, int) (*PipelineHistoryPage, error)
	GetPipelineStatus(string) (*PipelineStatus, error)
	PausePipeline(string, string) (*SimpleMessage, error)
	UnpausePipeline(string) (*SimpleMessage, error)
	UnlockPipeline(string) (*SimpleMessage, error)

	// Jobs API
	GetScheduledJobs() ([]*ScheduledJob, error)
	GetJobHistory(pipeline, stage, job string, offset int) ([]*JobHistory, error)

	// Environment Config API
	GetAllEnvironmentConfigs() ([]*EnvironmentConfig, error)
	GetEnvironmentConfig(name string) (*EnvironmentConfig, error)

	// Server health
	GetServerHealthMessages() ([]*ServerHealthMessage, error)
}

Client interface that exposes all the API methods supported by the underlying Client

func New

func New(host, username, password string) Client

New GoCD Client

type DefaultClient

type DefaultClient struct {
	Host    string `json:"host"`
	Request *gorequest.SuperAgent
}

DefaultClient entrypoint for GoCD

func (*DefaultClient) AgentRunJobHistory

func (c *DefaultClient) AgentRunJobHistory(uuid string, offset int) (*JobRunHistory, error)

AgentRunJobHistory - Lists the jobs that have executed on an agent.

func (*DefaultClient) DeleteAgent

func (c *DefaultClient) DeleteAgent(uuid string) error

DeleteAgent - Deletes an agent. PS: You must first disable an agent and ensure that its status is not Building, before attempting to deleting it.

func (*DefaultClient) DisableAgent

func (c *DefaultClient) DisableAgent(uuid string) error

DisableAgent - Disables an agent using it's UUID

func (*DefaultClient) EnableAgent

func (c *DefaultClient) EnableAgent(uuid string) error

EnableAgent - Enables an agent using it's UUID

func (*DefaultClient) GetAgent

func (c *DefaultClient) GetAgent(uuid string) (*Agent, error)

GetAgent - Gets an agent by its unique identifier (uuid)

func (*DefaultClient) GetAllAgents

func (c *DefaultClient) GetAllAgents() ([]*Agent, error)

GetAllAgents - Lists all available agents, these are agents that are present in the <agents/> tag inside cruise-config.xml and also agents that are in Pending state awaiting registration.

func (*DefaultClient) GetAllEnvironmentConfigs

func (c *DefaultClient) GetAllEnvironmentConfigs() ([]*EnvironmentConfig, error)

GetAllEnvironmentConfigs - Lists all available environments.

func (*DefaultClient) GetEnvironmentConfig

func (c *DefaultClient) GetEnvironmentConfig(name string) (*EnvironmentConfig, error)

GetEnvironmentConfig - Gets environment config for specified environment name.

func (*DefaultClient) GetJobHistory

func (c *DefaultClient) GetJobHistory(pipeline, stage, job string, offset int) ([]*JobHistory, error)

GetJobHistory - The job history allows users to list job instances of specified job. Supports pagination using offset which tells the API how many instances to skip.

func (*DefaultClient) GetPipelineGroups

func (c *DefaultClient) GetPipelineGroups() ([]*PipelineGroup, error)

GetPipelineGroups List pipeline groups along with the pipelines, stages and materials for each pipeline.

func (*DefaultClient) GetPipelineHistoryPage

func (c *DefaultClient) GetPipelineHistoryPage(name string, offset int) (*PipelineHistoryPage, error)

GetPipelineHistoryPage allows users to list pipeline instances. Supports pagination using offset which tells the API how many instances to skip. Note that te history is listed in reverse chronological order meaning the setting an offset to 1 will skip the last run of the pipeline and will give you a page of pipeline runs history which is 10 by default.

Example

ExampleDefaultClient_GetPipelineHistoryPage displays gets the pipeline runs from 2nd to the last to 15th to the last and displays informations about it. Uses the GetPipelineHistoryPage method.

client := gocd.New("http://localhost:8153", "admin", "badger")

offset := 2      // we ignore the 2 last pipeline runs
iterations := 15 // We want to stop iterating after we displayed 15 pipelines
for {
	h, err := client.GetPipelineHistoryPage("my-pipeline-name", offset)
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, p := range h.Pipelines {
		fmt.Printf("Run #%d pipeline %s was triggered by %s and ran the following stages:\n", p.Counter, p.Name, p.BuildCause.TriggerMessage)
		for _, stg := range p.Stages {
			fmt.Printf(" * %s with the jobs:\n", stg.Name)
			for _, job := range stg.Jobs {
				fmt.Printf("   * %s is currently %s (%s)\n", job.Name, job.State, job.Result)
			}
		}
		iterations--
		if iterations <= 0 {
			return
		}
	}
	offset = h.Pagination.Offset + h.Pagination.PageSize
	if h.Pagination.Total-offset <= 0 {
		break
	}
}
Output:

func (*DefaultClient) GetPipelineInstance

func (c *DefaultClient) GetPipelineInstance(name string, counter int) (*PipelineInstance, error)

GetPipelineInstance returns the pipeline instance corresponding to the given pipeline name and counter

Example

ExampleDefaultClient_GetPipelineInstance displays an instance of a pipeline run using the GetPipelineInstance method

client := gocd.New("http://localhost:8153", "admin", "badger")
p, err := client.GetPipelineInstance("my-pipeline-name", 911)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Printf("Run #%d pipeline %s was triggered by %s and ran the following stages:\n", p.Counter, p.Name, p.BuildCause.TriggerMessage)
for _, stg := range p.Stages {
	fmt.Printf(" * %s with the jobs:\n", stg.Name)
	for _, job := range stg.Jobs {
		fmt.Printf("   * %s is currently %s (%s)\n", job.Name, job.State, job.Result)
	}
}
Output:

func (*DefaultClient) GetPipelineStatus

func (c *DefaultClient) GetPipelineStatus(name string) (*PipelineStatus, error)

GetPipelineStatus allows users to check if the pipeline is paused, locked and schedulable.

Example

ExampleDefaultClient_GetPipelineStatus shows an example on how to use GetPipelineStatus

client := gocd.New("http://localhost:8153", "admin", "badger")
name := "my-pipeline-name"
p, err := client.GetPipelineStatus(name)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Printf("Pipeline %s status: %#v\n", name, p)
Output:

func (*DefaultClient) GetScheduledJobs

func (c *DefaultClient) GetScheduledJobs() ([]*ScheduledJob, error)

GetScheduledJobs - Lists all the current job instances which are scheduled but not yet assigned to any agent.

func (*DefaultClient) GetServerHealthMessages

func (c *DefaultClient) GetServerHealthMessages() ([]*ServerHealthMessage, error)

func (*DefaultClient) PausePipeline

func (c *DefaultClient) PausePipeline(name, cause string) (*SimpleMessage, error)

PausePipeline pauses the specified pipeline using the given cause

func (*DefaultClient) UnlockPipeline

func (c *DefaultClient) UnlockPipeline(name string) (*SimpleMessage, error)

UnlockPipeline releases a lock on a pipeline so that you can start up a new instance without having to wait for the earlier instance to finish. Note: A pipeline lock can only be released when a pipeline is locked, AND there is no running instance of the pipeline. Requires GoCD version 18.2.0+

func (*DefaultClient) UnpausePipeline

func (c *DefaultClient) UnpausePipeline(name string) (*SimpleMessage, error)

UnpausePipeline unpauses the specified pipeline

Example

ExampleDefaultClient_UnpausePipeline shows an example on how to use UnpausePipeline and double-checking the status with GetPipelineStatus

client := gocd.New("http://localhost:8153", "admin", "badger")
name := "my-pipeline-name"
p, err := client.GetPipelineStatus(name)
if err != nil {
	fmt.Println(err)
	return
}
if !p.Paused {
	_, err = client.UnpausePipeline(name)
	if err != nil {
		fmt.Println(err)
		return
	}
}
c, err := client.GetPipelineStatus(name)
if err != nil {
	fmt.Println(err)
	return
}
if c.Paused {
	fmt.Printf("Pipeline %s is now paused\n", name)
} else {
	fmt.Printf("Pipeline %s does seem to still be unpaused\n", name)
}
Output:

func (*DefaultClient) UpdateAgent

func (c *DefaultClient) UpdateAgent(uuid string, agent *Agent) (*Agent, error)

UpdateAgent - Update some attributes of an agent (uuid). Returns the updated agent properties

type EnvironmentConfig

type EnvironmentConfig struct {
	Name                 string                `json:"name,omitempty"`
	Pipelines            []string              `json:"pipelines"`
	Agents               []string              `json:"agents"`
	EnvironmentVariables []EnvironmentVariable `json:"environment_variables"`
}

EnvironmentConfig Object

func (*EnvironmentConfig) UnmarshalJSON

func (ec *EnvironmentConfig) UnmarshalJSON(b []byte) error

UnmarshalJSON overriding it for the dynamic material attributes type

type EnvironmentVariable

type EnvironmentVariable struct {
	Secure         bool   `json:"secure"`
	Name           string `json:"name"`
	Value          string `json:"value,omitempty"`
	EncryptedValue string `json:"encrypted_value,omitempty"`
}

EnvironmentVariable Object

type FreeSpace

type FreeSpace int

FreeSpace is required for GoCD API inconsistencies in agent free space scrape.

func (*FreeSpace) UnmarshalJSON

func (i *FreeSpace) UnmarshalJSON(data []byte) error

UnmarshalJSON expects an int or string ("unknown").

type Job

type Job struct {
	ID            int    `json:"id"`
	Name          string `json:"name"`
	Result        string `json:"result"`
	State         string `json:"state"`
	ScheduledDate int64  `json:"scheduled_date"`
}

Job definition used also by other elements like the pipeline and stages

type JobHistory

type JobHistory struct {
	AgentUUID           string               `json:"agent_uuid"`
	Name                string               `json:"name"`
	JobStateTransitions []JobStateTransition `json:"job_state_transitions"`
	ScheduledDate       int                  `json:"scheduled_date"`
	OriginalJobID       string               `json:"original_job_id"`
	PipelineCounter     int                  `json:"pipeline_counter"`
	PipelineName        string               `json:"pipeline_name"`
	Result              string               `json:"result"`
	State               string               `json:"state"`
	ID                  int                  `json:"id"`
	StageCounter        string               `json:"stage_counter"`
	StageName           string               `json:"stage_name"`
	ReRun               bool                 `json:"rerun"`
}

JobHistory - Represents an instance of a job from the past

type JobRunHistory

type JobRunHistory struct {
	Jobs       []*JobHistory `json:"jobs"`
	Pagination Pagination    `json:"pagination"`
}

type JobStateTransition

type JobStateTransition struct {
	StateChangeTime int    `json:"state_change_time,omitempty"`
	ID              int    `json:"id,omitempty"`
	State           string `json:"state,omitempty"`
}

JobStateTransition - Represents an instance of StateTransition the job went through

type LinkInXML

type LinkInXML struct {
	Rel  string `xml:"rel,attr"`
	Href string `xml:"href,attr"`
}

LinkInXML - <link rel="..." href="..."> tag

type Material

type Material struct {
	ID          int    `json:"id"`
	Type        string `json:"type"`
	Description string `json:"description"`
	Fingerprint string `json:"fingerprint"`
}

Material represents a material (Can be Git, Mercurial, Perforce, Subversion, Tfs, Pipeline, SCM)

type MaterialModification

type MaterialModification struct {
	ID           int    `json:"id"`
	ModifiedTime int64  `json:"modified_time"`
	UserName     string `json:"user_name"`
	EmailAddress string `json:"email_address"`
	Comment      string `json:"comment"`
	Revision     string `json:"revision"`
}

MaterialModification represents a modification done on a material configuration

type MaterialRevision

type MaterialRevision struct {
	Material      Material               `json:"material"`
	Modifications []MaterialModification `json:"modifications"`
	Changed       bool                   `json:"changed"`
}

MaterialRevision is a given revision of a material

type Pagination

type Pagination struct {
	Offset   int `json:"offset"`
	Total    int `json:"total"`
	PageSize int `json:"page_size"`
}

Pagination is a structure used in several places when the gocd api paginates the results. In the history of jobs and pipelines for example

type Pipeline

type Pipeline struct {
	Name      string     `json:"name,omitempty"`
	Label     string     `json:"label,omitempty"`
	Materials []Material `json:"materials,omitempty"`
	Stages    []string   `json:"stages,omitempty"`
}

Pipeline Object

type PipelineBuildCause

type PipelineBuildCause struct {
	Approver          string             `json:"approver"`
	MaterialRevisions []MaterialRevision `json:"material_revisions"`
	TriggerForced     bool               `json:"trigger_forced"`
	TriggerMessage    string             `json:"trigger_message"`
}

PipelineBuildCause represent what triggered the build of the pipeline

type PipelineGroup

type PipelineGroup struct {
	Name      string     `json:"name,omitempty"`
	Pipelines []Pipeline `json:"pipelines,omitempty"`
}

PipelineGroup Object

type PipelineHistoryPage

type PipelineHistoryPage struct {
	Pipelines  []PipelineInstance `json:"pipelines"`
	Pagination Pagination         `json:"pagination"`
}

PipelineHistoryPage represents a page of the history of run of a pipeline

type PipelineInstance

type PipelineInstance struct {
	ID                  int                `json:"id"`
	Name                string             `json:"name"`
	Label               string             `json:"label"`
	NaturalOrder        float32            `json:"natural_order"`
	CanRun              bool               `json:"can_run"`
	Comment             string             `json:"comment"`
	Counter             int                `json:"counter"`
	PreparingToSchedule bool               `json:"preparing_to_schedule"`
	Stages              []StageRun         `json:"stages"`
	BuildCause          PipelineBuildCause `json:"build_cause"`
}

PipelineInstance represents a pipeline instance (for a given run)

type PipelineStatus

type PipelineStatus struct {
	PausedCause string `json:"pausedCause"`
	PausedBy    string `json:"pausedBy"`
	Paused      bool   `json:"paused"`
	Schedulable bool   `json:"schedulable"`
	Locked      bool   `json:"locked"`
}

PipelineStatus represents the status of a pipeline

type ScheduledJob

type ScheduledJob struct {
	Name         string                 `xml:"name,attr"`
	JobID        string                 `xml:"id,attr"`
	BuildLocator string                 `xml:"buildLocator"`
	Link         LinkInXML              `xml:"link"`
	Environment  string                 `xml:"environment,omitempty"`
	RawResources []ScheduledJobResource `xml:"resources>resource,omitempty"`
}

ScheduledJob instance

func (*ScheduledJob) JobURL

func (sj *ScheduledJob) JobURL() string

JobURL - Full URL location of the scheduled job

func (*ScheduledJob) Resources

func (sj *ScheduledJob) Resources() []string

Resources - return resources as []string

type ScheduledJobResource

type ScheduledJobResource struct {
	Name string `xml:",chardata"`
}

ScheduledJobResource wrapper for resources > resource

type ServerHealthMessage

type ServerHealthMessage struct {
	Message string `json:"message"`
	Detail  string `json:"detail"`
	Level   string `json:"level"`
	Time    string `json:"time"`
}

func (*ServerHealthMessage) IsError

func (s *ServerHealthMessage) IsError() bool

func (*ServerHealthMessage) IsWarning

func (s *ServerHealthMessage) IsWarning() bool

type SimpleMessage

type SimpleMessage struct {
	Message string `json:"message"`
}

SimpleMessage is in general the structure returned by the POST queries sent to GoCD.

type StageRun

type StageRun struct {
	ID                int    `json:"id"`
	Name              string `json:"name"`
	ApprovedBy        string `json:"approved_by"`
	Jobs              []Job  `json:"jobs"`
	CanRun            bool   `json:"can_run"`
	Result            string `json:"result"`
	ApprovalType      string `json:"approval_type"`
	Counter           string `json:"counter"`
	OperatePermission bool   `json:"operate_permission"`
	RerunOfCounter    bool   `json:"rerun_of_counter"`
	Scheduled         bool   `json:"scheduled"`
}

StageRun represent a stage run history event

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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