Module: Hudson::Api

Includes:
HTTParty
Defined in:
lib/hudson/api.rb

Constant Summary collapse

JobAlreadyExistsError =

http_proxy ‘localhost’, ‘8888’

Class.new(Exception)

Class Method Summary collapse

Class Method Details

.add_node(options = {}) ⇒ Object

Adds SSH nodes only, for now



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/hudson/api.rb', line 108

def self.add_node(options = {})
  options = options.with_clean_keys
  default_options = Hash.new
  default_options.merge!(
    :slave_port  => 22,
    :master_key  => "/home/deploy/.ssh/id_rsa", # FIXME - hardcoded master username assumption
    :slave_fs    => "/data/hudson-slave/",
    :description => "Automatically created by Hudson.rb",
    :executors   => 2,
    :exclusive   => true
  )

  slave_host = options[:slave_host]
  name       = options[:name] || slave_host

  options    = default_options.merge(options)
  
  type = "hudson.slaves.DumbSlave$DescriptorImpl"

  fields = {
    "name" => name,
    "type" => type,

    "json"                => {
      "name"              => name,
      "nodeDescription"   => options[:description],
      "numExecutors"      => options[:executors],
      "remoteFS"          => options[:slave_fs],
      "labelString"       => options[:label],
      "mode"              => options[:exclusive] ? "EXCLUSIVE" : "NORMAL",
      "type"              => type,
      "retentionStrategy" => { "stapler-class"  => "hudson.slaves.RetentionStrategy$Always" },
      "nodeProperties"    => { "stapler-class-bag" => "true" },
      "launcher"          => {
        "stapler-class" => "hudson.plugins.sshslaves.SSHLauncher",
        "host"          => slave_host,
        "port"          => options[:slave_port],
        "username"      => options[:slave_user],
        "privatekey"    => options[:master_key],
      }
    }.to_json
  }

  url = URI.parse("#{base_uri}/computer/doCreateItem")

  req = Net::HTTP::Post.new(url.path)
  req.set_form_data(fields)

  http = Net::HTTP.new(url.host, url.port)

  response = http.request(req)
  case response
  when Net::HTTPFound
    true
  else
    # error message looks like:
    # <td id="main-panel">
    # <h1>Error</h1><p>Slave called 'localhost' already exists</p>
    require "hpricot"
    error = Hpricot(response.body).search("td#main-panel p").text
    unless error.blank?
      puts error
    else
      puts response.body # so we can find other errors
    end
    false
  end
end

.build_job(name) ⇒ Object



69
70
71
72
# File 'lib/hudson/api.rb', line 69

def self.build_job(name)
  res = get_plain "/job/#{name}/build"
  res.code.to_i == 302
end

.create_job(name, job_config, options = {}) ⇒ Object

returns true if successfully create a new job on Hudson job_config is a Hudson::JobConfigBuilder instance options are:

:override - true, will delete any existing job with same name, else error

returns true if successful, else false

TODO Exceptions?



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/hudson/api.rb', line 40

def self.create_job(name, job_config, options = {})
  options = options.with_clean_keys
  delete_job(name) if options[:override]
  begin
    res = post "/createItem/api/xml?name=#{CGI.escape(name)}", {
      :body => job_config.to_xml, :format => :xml, :headers => { 'content-type' => 'application/xml' }
    }
    if res.code.to_i == 200
      cache_base_uri
      true
    else
      # TODO - what are the errors we get?
      puts "Server error:"
      p res.code
      puts res.body
      false
    end
  rescue REXML::ParseException => e
    # For some reason, if the job exists we get back half a page of HTML
    raise JobAlreadyExistsError.new(name)
  end
end

.delete_job(name) ⇒ Object

Attempts to delete a job name



64
65
66
67
# File 'lib/hudson/api.rb', line 64

def self.delete_job(name)
  res = post_plain "#{job_url name}/doDelete"
  res.code.to_i == 302
end

.delete_node(name) ⇒ Object



177
178
179
# File 'lib/hudson/api.rb', line 177

def self.delete_node(name)
  post_plain("#{base_uri}/computer/#{CGI::escape(name).gsub('+', '%20')}/doDelete/api/json")
end

.get_plain(path, options = {}) ⇒ Object

Helper for GET that don’t barf at Hudson’s crappy API responses



189
190
191
192
193
# File 'lib/hudson/api.rb', line 189

def self.get_plain(path, options = {})
  options = options.with_clean_keys
  uri = URI.parse base_uri
  res = Net::HTTP.start(uri.host, uri.port) { |http| http.get(path, options) }
end

.job(name) ⇒ Object

Return hash of job statuses



85
86
87
88
89
90
91
92
93
94
95
# File 'lib/hudson/api.rb', line 85

def self.job(name)
  begin
    json = get "/job/#{name}/api/json"
    cache_base_uri
    json
  rescue Errno::ECONNREFUSED
    false
  rescue Errno::EAFNOSUPPORT
    false
  end
end

.job_namesObject



80
81
82
# File 'lib/hudson/api.rb', line 80

def self.job_names
  summary["jobs"].map {|job| job["name"]}
end

.nodesObject



97
98
99
100
101
102
103
104
105
# File 'lib/hudson/api.rb', line 97

def self.nodes
  json = get "/computer/api/json"
  cache_base_uri
  json
rescue Errno::ECONNREFUSED => e
  false
rescue Errno::EAFNOSUPPORT
  false
end

.post_plain(path, options = {}) ⇒ Object

Helper for POST that don’t barf at Hudson’s crappy API responses



182
183
184
185
186
# File 'lib/hudson/api.rb', line 182

def self.post_plain(path, options = {})
  options = options.with_clean_keys
  uri = URI.parse base_uri
  res = Net::HTTP.start(uri.host, uri.port) { |http| http.post(path, options) }
end

.setup_base_url(options) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/hudson/api.rb', line 19

def self.setup_base_url(options)
  options = options.with_clean_keys
  # Thor's HashWithIndifferentAccess is based on string keys which URI::HTTP.build ignores
  options = options.inject({}) { |mem, (key, val)| mem[key.to_sym] = val; mem }
  options[:host] ||= ENV['HUDSON_HOST']
  options[:port] ||= ENV['HUDSON_PORT']
  options[:port] &&= options[:port].to_i
  return false unless options[:host] || Hudson::Config.config["base_uri"]
  uri = options[:host] ? URI::HTTP.build(options) : Hudson::Config.config["base_uri"]
  base_uri uri.to_s
  uri
end

.summaryObject



74
75
76
77
78
# File 'lib/hudson/api.rb', line 74

def self.summary
  json = get "/api/json"
  cache_base_uri
  json
end