Skip to content

Commit

Permalink
update issues on jobs listing
Browse files Browse the repository at this point in the history
Signed-off-by: Jeeva Kandasamy <[email protected]>
  • Loading branch information
jkandasa committed Jun 22, 2021
1 parent a1efe20 commit 9c3ad49
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 37 deletions.
33 changes: 25 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Inspired by `kubectl` and `oc` (OpenShift) client.

### Download the client
* [Releases](https://github.com/jkandasa/jenkinsctl/releases)
* [Releases](https://github.com/jkandasa/jenkinsctl/releases/latest)

### Examples
To get login token,
Expand All @@ -24,12 +24,21 @@ Server Version: 2.289.1
```
#### Display jobs
```bash
# display jobs
$ jenkinsctl jobs
NAME CLASS
JobFolder1 com.cloudbees.hudson.plugins.folder.Folder
test-job-1 hudson.model.FreeStyleProject
test-job-2 hudson.model.FreeStyleProject
$ go run cmd/main.go jobs
COLOR NAME CLASS URL
JobFolder1/job/Foleder2 com.cloudbees.hudson.plugins.folder.Folder http://localhost:8080/job/JobFolder1/job/Foleder2/
notbuilt JobFolder1/job/folder-job1 hudson.model.FreeStyleProject http://localhost:8080/job/JobFolder1/job/folder-job1/
red pipeline job org.jenkinsci.plugins.workflow.job.WorkflowJob http://localhost:8080/job/pipeline%20job/
blue test-job-1 hudson.model.FreeStyleProject http://localhost:8080/job/test-job-1/
notbuilt test-job-2 hudson.model.FreeStyleProject http://localhost:8080/job/test-job-2/

$ go run cmd/main.go jobs --depth 2
COLOR NAME CLASS URL
blue JobFolder1/job/Foleder2/job/hello-job 123 hudson.model.FreeStyleProject http://localhost:8080/job/JobFolder1/job/Foleder2/job/hello-job%20123/
notbuilt JobFolder1/job/folder-job1 hudson.model.FreeStyleProject http://localhost:8080/job/JobFolder1/job/folder-job1/
red pipeline job org.jenkinsci.plugins.workflow.job.WorkflowJob http://localhost:8080/job/pipeline%20job/
blue test-job-1 hudson.model.FreeStyleProject http://localhost:8080/job/test-job-1/
notbuilt test-job-2 hudson.model.FreeStyleProject http://localhost:8080/job/test-job-2/
```

#### Switch to a job
Expand Down Expand Up @@ -180,7 +189,7 @@ $ jenkinsctl get build 11 --output json --pretty
"artifacts": null
```
#### Display the console log of a build
```
```bash
$ jenkinsctl get console 11
Started by user Jeeva Kandasamy
Running as SYSTEM
Expand All @@ -193,4 +202,12 @@ Mon 21 Jun 2021 04:56:09 PM UTC
+ hostname
33501f943b12
Finished: SUCCESS

# watch running builds console logs
$ jenkinsctl get console 12 --watch
Started by user Jeeva Kandasamy
Running as SYSTEM
Building in workspace /var/jenkins_home/workspace/test-job-1
[test-job-1] $ /bin/sh -xe /tmp/jenkins2269490024621194842.sh
...
```
2 changes: 1 addition & 1 deletion cmd/command/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ var createResource = &cobra.Command{
return
}

client := jenkins.NewClient(CONFIG)
client := jenkins.NewClient(CONFIG, &ioStreams)
if client == nil {
return
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/command/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ var downloadArtifacts = &cobra.Command{
Short: "Download artifact of a build",
Example: ` jenkinsctl download artifact --build-number 2101 --to-dir /tmp/artifacts`,
Run: func(cmd *cobra.Command, args []string) {
client := jenkins.NewClient(CONFIG)
client := jenkins.NewClient(CONFIG, &ioStreams)
if client == nil {
return
}

savedLocation, err := client.DownloadArtifacts(ioStreams.Out, CONFIG.JobContext, buildNumber, artifactSaveLocation)
savedLocation, err := client.DownloadArtifacts(CONFIG.JobContext, buildNumber, artifactSaveLocation)
if err != nil {
fmt.Fprintf(ioStreams.ErrOut, "error on downloading artifacts. error:[%s]\n", err)
return
Expand Down
10 changes: 5 additions & 5 deletions cmd/command/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ var getBuilds = &cobra.Command{
jenkinsctl get build 61`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
client := jenkins.NewClient(CONFIG)
client := jenkins.NewClient(CONFIG, &ioStreams)
if client == nil {
return
}
Expand Down Expand Up @@ -172,7 +172,7 @@ var getParameters = &cobra.Command{
# get parametes as yaml
jenkinsctl get parameters --output yaml`,
Run: func(cmd *cobra.Command, args []string) {
client := jenkins.NewClient(CONFIG)
client := jenkins.NewClient(CONFIG, &ioStreams)
if client == nil {
return
}
Expand Down Expand Up @@ -218,15 +218,15 @@ var getConsole = &cobra.Command{
return
}

client := jenkins.NewClient(CONFIG)
client := jenkins.NewClient(CONFIG, &ioStreams)
if client == nil {
return
}

consoleLog, err := client.GetConsole(CONFIG.JobContext, buildNumber, watch, ioStreams.Out)
consoleLog, err := client.GetConsole(CONFIG.JobContext, buildNumber, watch)
if err != nil {
if err.Error() == "404" {
fmt.Fprintf(ioStreams.ErrOut, "there is no build wih number %d\n", buildNumber)
fmt.Fprintf(ioStreams.ErrOut, "there is no build number %d\n", buildNumber)
return
}
fmt.Fprintf(ioStreams.ErrOut, "error on listing build console. error:%s\n", err.Error())
Expand Down
4 changes: 2 additions & 2 deletions cmd/command/job_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ var jobContextCmd = &cobra.Command{
fmt.Fprintf(ioStreams.ErrOut, "Current job '%s' at '%s'\n", CONFIG.JobContext, CONFIG.URL)
return
}
client := jenkins.NewClient(CONFIG)
client := jenkins.NewClient(CONFIG, &ioStreams)
if client != nil {
CONFIG.JobContext = strings.TrimSpace(args[0])
WriteConfigFile()
Expand All @@ -52,7 +52,7 @@ var getJobs = &cobra.Command{
# display existing jobs with depth flag
jenkinsctl jobs --depth 2`,
Run: func(cmd *cobra.Command, args []string) {
client := jenkins.NewClient(CONFIG)
client := jenkins.NewClient(CONFIG, &ioStreams)
if client == nil {
return
}
Expand Down
12 changes: 10 additions & 2 deletions cmd/command/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ var loginCmd = &cobra.Command{
Use: "login",
Short: "Log in to a server",
Example: ` # login to the server with username and password/token
export TOKEN=$(cat my_token.txt)
jenkinsctl login http://localhost:8080 --username jenkins --password ${TOKEN}
# login to the server with username and password/token
jenkinsctl login http://localhost:8080 --username jenkins --password my_token
# login to the insecure server (with SSL certificate)
Expand All @@ -37,7 +41,7 @@ var loginCmd = &cobra.Command{
CONFIG.Username = username
CONFIG.Password = password
CONFIG.InsecureSkipTLSVerify = insecureSkipTLSVerify
client := jenkins.NewClient(CONFIG)
client := jenkins.NewClient(CONFIG, &ioStreams)
if client != nil {
fmt.Fprintln(ioStreams.ErrOut, "Login successful.")
WriteConfigFile()
Expand All @@ -51,12 +55,16 @@ var logoutCmd = &cobra.Command{
Example: ` # logout from a server
jenkinsctl logout`,
Run: func(cmd *cobra.Command, args []string) {
if CONFIG.URL == "" {
fmt.Fprintln(ioStreams.ErrOut, "There is no connection information.")
return
}
CONFIG.URL = ""
CONFIG.Username = ""
CONFIG.Password = ""
CONFIG.InsecureSkipTLSVerify = false
CONFIG.JobContext = ""
fmt.Fprintln(ioStreams.ErrOut, "Logout successful.")
fmt.Fprintln(ioStreams.Out, "Logout successful.")
WriteConfigFile()
},
}
2 changes: 1 addition & 1 deletion cmd/command/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ var statusCmd = &cobra.Command{
Use: "status",
Short: "Displays an overview of the jenkins server",
Run: func(cmd *cobra.Command, args []string) {
client := jenkins.NewClient(CONFIG)
client := jenkins.NewClient(CONFIG, &ioStreams)
if client == nil {
return
}
Expand Down
6 changes: 5 additions & 1 deletion cmd/command/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ var versionCmd = &cobra.Command{
Short: "Print the client and server version information",
Run: func(cmd *cobra.Command, args []string) {
fmt.Fprintln(ioStreams.Out, "Client Version:", version.Get().String())
client := jenkins.NewClient(CONFIG)
if CONFIG.URL == "" {
fmt.Fprintln(ioStreams.Out, "Server Version: not logged in")
return
}
client := jenkins.NewClient(CONFIG, &ioStreams)
if client != nil {
fmt.Fprintln(ioStreams.Out, "Server Version:", client.Version())
}
Expand Down
35 changes: 21 additions & 14 deletions pkg/jenkins/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"crypto/tls"
"fmt"
"io"
"log"
"net/http"
"os"
Expand All @@ -14,18 +13,20 @@ import (
"time"

"github.com/bndr/gojenkins"
"github.com/jkandasa/jenkinsctl/pkg/model"
"github.com/jkandasa/jenkinsctl/pkg/model/config"
jenkinsML "github.com/jkandasa/jenkinsctl/pkg/model/jenkins"
)

// Client type
type Client struct {
api *gojenkins.Jenkins
ctx context.Context
ioStreams *model.IOStreams
api *gojenkins.Jenkins
ctx context.Context
}

// NewClient function to get client instance
func NewClient(cfg *config.Config) *Client {
func NewClient(cfg *config.Config, streams *model.IOStreams) *Client {
httpClient := http.DefaultClient
httpClient.Transport = http.DefaultTransport
httpClient.Transport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: cfg.InsecureSkipTLSVerify}
Expand All @@ -36,7 +37,7 @@ func NewClient(cfg *config.Config) *Client {
if err != nil {
log.Fatalf("error on login, %s", err.Error())
}
return &Client{api: jenkins, ctx: ctx}
return &Client{api: jenkins, ctx: ctx, ioStreams: streams}
}

func (jc *Client) Version() string {
Expand All @@ -59,7 +60,7 @@ func (jc *Client) ListJobs(depth int) ([]gojenkins.InnerJob, error) {
if err != nil {
return nil, err
}
receivedJobs, err := jc.getInnerJobs(job, 0, depth)
receivedJobs, err := jc.getInnerJobs(job.GetName(), job, 0, depth)
if err != nil {
return nil, err
}
Expand All @@ -73,9 +74,14 @@ func (jc *Client) ListJobs(depth int) ([]gojenkins.InnerJob, error) {
return finalJobs, nil
}

func (jc *Client) getInnerJobs(job *gojenkins.Job, depth, limit int) ([]gojenkins.InnerJob, error) {
func (jc *Client) getInnerJobs(parent string, job *gojenkins.Job, depth, limit int) ([]gojenkins.InnerJob, error) {
if depth == limit {
return nil, nil
if job == nil {
return nil, nil
}
return []gojenkins.InnerJob{{
Color: job.GetDetails().Color, Name: parent,
Class: job.GetDetails().Class, Url: job.GetDetails().URL}}, nil
}
finalJobs := make([]gojenkins.InnerJob, 0)

Expand All @@ -84,8 +90,9 @@ func (jc *Client) getInnerJobs(job *gojenkins.Job, depth, limit int) ([]gojenkin
return nil, err
}
for _, jobInner := range jobsList {
jobName := fmt.Sprintf("%s/job/%s", parent, jobInner.GetName())
if jobInner.GetDetails().Class == "com.cloudbees.hudson.plugins.folder.Folder" {
receivedJobs, err := jc.getInnerJobs(jobInner, depth+1, limit)
receivedJobs, err := jc.getInnerJobs(jobName, jobInner, depth+1, limit)
if err != nil {
return nil, err
}
Expand All @@ -94,7 +101,7 @@ func (jc *Client) getInnerJobs(job *gojenkins.Job, depth, limit int) ([]gojenkin
}
} else {
finalJobs = append(finalJobs, gojenkins.InnerJob{
Color: jobInner.GetDetails().Color, Name: jobInner.GetDetails().FullName,
Color: jobInner.GetDetails().Color, Name: jobName,
Class: jobInner.GetDetails().Class, Url: jobInner.GetDetails().URL})
}
}
Expand Down Expand Up @@ -198,7 +205,7 @@ func (jc *Client) ListBuilds(jobName string, limit int, withConsole bool) ([]jen
}

// GetConsole returns/prints build console log
func (jc *Client) GetConsole(jobName string, buildNumber int, watch bool, out io.Writer) (string, error) {
func (jc *Client) GetConsole(jobName string, buildNumber int, watch bool) (string, error) {
build, err := jc.api.GetBuild(jc.ctx, jobName, int64(buildNumber))
if err != nil {
return "", err
Expand All @@ -218,7 +225,7 @@ func (jc *Client) GetConsole(jobName string, buildNumber int, watch bool, out io
return "", err
}
if len(console.Content) > 0 {
fmt.Fprint(out, console.Content)
fmt.Fprint(jc.ioStreams.Out, console.Content)
}
startID = console.Offset
if !console.HasMoreText {
Expand All @@ -239,7 +246,7 @@ func (jc *Client) ListParameters(jobName string) ([]gojenkins.ParameterDefinitio
}

// DownloadArtifacts of a build
func (jc *Client) DownloadArtifacts(out io.Writer, jobName string, buildNumber int, toDirectory string) (string, error) {
func (jc *Client) DownloadArtifacts(jobName string, buildNumber int, toDirectory string) (string, error) {
directoryFinal := filepath.Join(toDirectory, jobName, strconv.Itoa(buildNumber))
build, err := jc.api.GetBuild(jc.ctx, jobName, int64(buildNumber))
if err != nil {
Expand All @@ -251,7 +258,7 @@ func (jc *Client) DownloadArtifacts(out io.Writer, jobName string, buildNumber i
artifacts := build.GetArtifacts()

if len(artifacts) == 0 {
fmt.Fprintln(out, "no artifacts found")
fmt.Fprintln(jc.ioStreams.Out, "no artifacts found")
return "", nil
}

Expand Down
3 changes: 2 additions & 1 deletion scripts/version.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ export GIT_SHA=`git rev-parse HEAD`
export GIT_SHA_SHORT=`git rev-parse --short HEAD`
export VERSION_PKG="github.com/jkandasa/jenkinsctl/pkg/version"

export LD_FLAGS="-X $VERSION_PKG.version=$GIT_BRANCH -X $VERSION_PKG.buildDate=$BUILD_DATE -X $VERSION_PKG.gitCommit=$GIT_SHA"

# update tag, if available
if [ ${GIT_BRANCH} = "HEAD" ]; then
Expand All @@ -21,3 +20,5 @@ export VERSION=`echo ${GIT_BRANCH} | awk 'match($0, /([0-9]*\.[0-9]*\.[0-9]*)$/
if [ ${GIT_BRANCH} = "master" ]; then
export VERSION="master"
fi

export LD_FLAGS="-X $VERSION_PKG.version=$VERSION -X $VERSION_PKG.buildDate=$BUILD_DATE -X $VERSION_PKG.gitCommit=$GIT_SHA"

0 comments on commit 9c3ad49

Please sign in to comment.