Class: JenkinsApi::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/jenkins_api_client/client.rb,
lib/jenkins_api_client/job.rb,
lib/jenkins_api_client/node.rb,
lib/jenkins_api_client/view.rb,
lib/jenkins_api_client/system.rb,
lib/jenkins_api_client/version.rb,
lib/jenkins_api_client/build_queue.rb

Overview

This is the client class that acts as the bridge between the subclasses and Jnekins. This class contains methods that performs GET and POST requests for various operations.

Defined Under Namespace

Classes: BuildQueue, Job, Node, System, View

Constant Summary collapse

DEFAULT_SERVER_PORT =

Default port to be used to connect to Jenkins

8080
DEFAULT_TIMEOUT =

Default timeout in seconds to be used while performing operations

120
VALID_PARAMS =

Parameters that are permitted as options while initializing the client

[
  "server_url",
  "server_ip",
  "server_port",
  "proxy_ip",
  "proxy_port",
  "jenkins_path",
  "username",
  "password",
  "password_base64",
  "debug",
  "timeout",
  "ssl",
  "follow_redirects"
].freeze
MAJOR =

Major version of the gem

0
MINOR =

Minor version of the gem

12
TINY =

Tiny version of the gem used for patches

0
PRE =

Used for pre-releases

nil
VERSION =

Version String of Jenkins API Client.

[MAJOR, MINOR, TINY, PRE].compact.join('.')

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ JenkinsApi::Client

Initialize a Client object with Jenkins CI server credentials

Parameters:

  • args (Hash)
    • the :server_ip param is the IP address of the Jenkins CI server

    • the :server_port param is the port on which the Jenkins listens

    • the :server_url param is the full URL address of the Jenkins CI server (http/https)

    • the :username param is the username used for connecting to the server (optional)

    • the :password param is the password for connecting to the CI server (optional)

    • the :proxy_ip param is the proxy IP address

    • the :proxy_port param is the proxy port

    • the :jenkins_path param is the optional context path for Jenkins

    • the :ssl param indicates if Jenkins is accessible over HTTPS (defaults to false)

    • the :follow_redirects param will cause the client to follow a redirect (jenkins can return a 30x when starting a build)

Raises:

  • (ArgumentError)

    when required options are not provided.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/jenkins_api_client/client.rb', line 81

def initialize(args)
  args.each do |key, value|
    if value && VALID_PARAMS.include?(key.to_s)
      instance_variable_set("@#{key}", value)
    end
  end if args.is_a? Hash
  unless @server_ip || @server_url
    raise ArgumentError, "Server IP or Server URL is required to connect to Jenkins"
  end
  # Username/password are optional as some jenkins servers do not require auth
  if @username && !(@password || @password_base64)
    raise ArgumentError, "If username is provided, password is required"
  end
  if @proxy_ip.nil? ^ @proxy_port.nil?
    raise ArgumentError, "Proxy IP and port must both be specified or" +
      " both left nil"
  end
  @server_uri = URI.parse(@server_url) if @server_url
  @server_port = DEFAULT_SERVER_PORT unless @server_port
  @timeout = DEFAULT_TIMEOUT unless @timeout
  @ssl ||= false
  @ssl = @server_uri.scheme == "https" if @server_uri
  @debug = false unless @debug

  # Base64 decode inserts a newline character at the end. As a workaround
  # added chomp to remove newline characters. I hope nobody uses newline
  # characters at the end of their passwords :)
  @password = Base64.decode64(@password_base64).chomp if @password_base64
end

Instance Attribute Details

#debugObject

Returns the value of attribute debug.



39
40
41
# File 'lib/jenkins_api_client/client.rb', line 39

def debug
  @debug
end

#timeoutObject

Returns the value of attribute timeout.



39
40
41
# File 'lib/jenkins_api_client/client.rb', line 39

def timeout
  @timeout
end

Instance Method Details

#api_get_request(url_prefix, tree = nil, url_suffix = "/api/json", raw_response = false) ⇒ String, JSON

Sends a GET request to the Jenkins CI server with the specified URL

Parameters:

  • url_prefix (String)

    The prefix to use in the URL

  • tree (String) (defaults to: nil)

    A specific JSON tree to optimize the API call

  • url_suffix (String) (defaults to: "/api/json")

    The suffix to be used in the URL

  • raw_response (Boolean) (defaults to: false)

    Return complete Response object instead of JSON body of response

Returns:

  • (String, JSON)

    JSON response from Jenkins



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/jenkins_api_client/client.rb', line 224

def api_get_request(url_prefix, tree = nil, url_suffix ="/api/json",
                    raw_response = false)
  url_prefix = "#{@jenkins_path}#{url_prefix}"
  to_get = ""
  if tree
    to_get = "#{url_prefix}#{url_suffix}?#{tree}"
  else
    to_get = "#{url_prefix}#{url_suffix}"
  end
  to_get = URI.escape(to_get)
  request = Net::HTTP::Get.new(to_get)
  puts "[INFO] GET #{to_get}" if @debug
  response = make_http_request(request)
  if raw_response
    response
  else
    handle_exception(response, "body", url_suffix =~ /json/)
  end
end

#api_post_request(url_prefix, form_data = {}) ⇒ String

Sends a POST message to the Jenkins CI server with the specified URL

Parameters:

  • url_prefix (String)

    The prefix to be used in the URL

  • form_data (Hash) (defaults to: {})

    Form data to send with POST request

Returns:

  • (String)

    Response code form Jenkins Response



251
252
253
254
255
256
257
258
259
260
261
# File 'lib/jenkins_api_client/client.rb', line 251

def api_post_request(url_prefix, form_data = {})
  # Added form_data default {} instead of nil to help with proxies
  # that barf with empty post
  url_prefix = URI.escape("#{@jenkins_path}#{url_prefix}")
  request = Net::HTTP::Post.new("#{url_prefix}")
  puts "[INFO] POST #{url_prefix}" if @debug
  request.content_type = 'application/json'
  request.set_form_data(form_data)
  response = make_http_request(request)
  handle_exception(response)
end

#exec_cli(command, args = []) ⇒ String

Execute the Jenkins CLI

Parameters:

  • command (String)

    command name

  • args (Array) (defaults to: [])

    the arguments for the command

Returns:

  • (String)

    command output from the CLI

Raises:



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/jenkins_api_client/client.rb', line 331

def exec_cli(command, args = [])
  base_dir = File.dirname(__FILE__)
  server_url = "http://#{@server_ip}:#{@server_port}/#{@jenkins_path}"
  cmd = "java -jar #{base_dir}/../../java_deps/jenkins-cli.jar" +
    " -s #{server_url} #{command}" +
    " --username #{@username} --password #{@password} " +
    args.join(' ')
  java_cmd = Mixlib::ShellOut.new(cmd)

  # Run the command
  java_cmd.run_command
  if java_cmd.stderr.empty?
    java_cmd.stdout.chomp
  else
    # The stderr has a stack trace of the Java program. We'll already have
    # a stack trace for Ruby. So just display a descriptive message for the
    # error thrown by the CLI.
    raise Exceptions::CLIException.new(java_cmd.stderr.split("\n").first)
  end
end

#get_config(url_prefix) ⇒ String

Obtains the configuration of a component from the Jenkins CI server

Parameters:

  • url_prefix (String)

    The prefix to be used in the URL

Returns:

  • (String)

    XML configuration obtained from Jenkins



269
270
271
272
273
274
275
# File 'lib/jenkins_api_client/client.rb', line 269

def get_config(url_prefix)
  url_prefix = URI.escape("#{@jenkins_path}#{url_prefix}")
  request = Net::HTTP::Get.new("#{url_prefix}/config.xml")
  puts "[INFO] GET #{url_prefix}/config.xml" if @debug
  response = make_http_request(request)
  handle_exception(response, "body")
end

#get_hudson_versionString

Obtain the Hudson version of the CI server

Returns:

  • (String)

    Version of Hudson on Jenkins server



307
308
309
310
# File 'lib/jenkins_api_client/client.rb', line 307

def get_hudson_version
  response = get_root
  response["X-Hudson"]
end

#get_jenkins_versionString

Obtain the version of Jenkins CI server

Returns:

  • (String)

    Version of Jenkins



298
299
300
301
# File 'lib/jenkins_api_client/client.rb', line 298

def get_jenkins_version
  response = get_root
  response["X-Jenkins"]
end

#get_rootNet::HTTP::Response

Obtains the root of Jenkins server. This function is used to see if Jenkins is running

Returns:

  • (Net::HTTP::Response)

    Response from Jenkins for “/”



209
210
211
212
# File 'lib/jenkins_api_client/client.rb', line 209

def get_root
  request = Net::HTTP::Get.new("/")
  make_http_request(request)
end

#get_server_dateString

Obtain the date of the Jenkins server

Returns:

  • (String)

    Server date



316
317
318
319
# File 'lib/jenkins_api_client/client.rb', line 316

def get_server_date
  response = get_root
  response["Date"]
end

#jobJenkinsApi::Client::Job

Creates an instance to the Job class by passing a reference to self

Returns:



121
122
123
# File 'lib/jenkins_api_client/client.rb', line 121

def job
  JenkinsApi::Client::Job.new(self)
end

#nodeJenkinsApi::Client::Node

Creates an instance to the Node class by passing a reference to self

Returns:



137
138
139
# File 'lib/jenkins_api_client/client.rb', line 137

def node
  JenkinsApi::Client::Node.new(self)
end

#post_config(url_prefix, xml) ⇒ String

Posts the given xml configuration to the url given

Parameters:

  • url_prefix (String)

    The prefix to be used in the URL

  • xml (String)

    The XML configuration to be sent to Jenkins

Returns:

  • (String)

    Response code returned from Jenkins



284
285
286
287
288
289
290
291
292
# File 'lib/jenkins_api_client/client.rb', line 284

def post_config(url_prefix, xml)
  url_prefix = URI.escape("#{@jenkins_path}#{url_prefix}")
  request = Net::HTTP::Post.new("#{url_prefix}")
  puts "[INFO] POST #{url_prefix}" if @debug
  request.body = xml
  request.content_type = 'application/xml'
  response = make_http_request(request)
  handle_exception(response)
end

#queueJenkinsApi::Client::BuildQueue

Creates an instance to the BuildQueue by passing a reference to self

Returns:



153
154
155
# File 'lib/jenkins_api_client/client.rb', line 153

def queue
  JenkinsApi::Client::BuildQueue.new(self)
end

#systemJenkinsApi::Client::System

Creates an instance to the System class by passing a reference to self

Returns:



129
130
131
# File 'lib/jenkins_api_client/client.rb', line 129

def system
  JenkinsApi::Client::System.new(self)
end

#to_sString

Returns a string representing the class name

Returns:

  • (String)

    string representation of class name



161
162
163
# File 'lib/jenkins_api_client/client.rb', line 161

def to_s
  "#<JenkinsApi::Client>"
end

#toggle_debugObject

This method toggles the debug parameter in run time



113
114
115
# File 'lib/jenkins_api_client/client.rb', line 113

def toggle_debug
  @debug = @debug == false ? true : false
end

#viewJenkinsApi::Client::View

Creates an instance to the View class by passing a reference to self

Returns:



145
146
147
# File 'lib/jenkins_api_client/client.rb', line 145

def view
  JenkinsApi::Client::View.new(self)
end