Class: CloudstackClient::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/knife-cloudstack/connection.rb

Constant Summary collapse

ASYNC_POLL_INTERVAL =
5.0
ASYNC_TIMEOUT =
300

Instance Method Summary collapse

Constructor Details

#initialize(api_url, api_key, secret_key) ⇒ Connection

Returns a new instance of Connection.



35
36
37
38
39
# File 'lib/knife-cloudstack/connection.rb', line 35

def initialize(api_url, api_key, secret_key)
  @api_url = api_url
  @api_key = api_key
  @secret_key = secret_key
end

Instance Method Details

#associate_ip_address(zone_id) ⇒ Object

Acquires and associates a public IP to an account.



469
470
471
472
473
474
475
476
477
# File 'lib/knife-cloudstack/connection.rb', line 469

def associate_ip_address(zone_id)
  params = {
      'command' => 'associateIpAddress',
      'zoneId' => zone_id
  }

  json = send_async_request(params)
  json['ipaddress']
end

#create_port_forwarding_rule(ip_address_id, private_port, protocol, public_port, virtual_machine_id) ⇒ Object

Creates a port forwarding rule.



520
521
522
523
524
525
526
527
528
529
530
531
# File 'lib/knife-cloudstack/connection.rb', line 520

def create_port_forwarding_rule(ip_address_id, private_port, protocol, public_port, virtual_machine_id)
  params = {
      'command' => 'createPortForwardingRule',
      'ipAddressId' => ip_address_id,
      'privatePort' => private_port,
      'protocol' => protocol,
      'publicPort' => public_port,
      'virtualMachineId' => virtual_machine_id
  }
  json = send_async_request(params)
  json['portforwardingrule']
end

#create_server(host_name, service_name, template_name, zone_name = nil, network_names = []) ⇒ Object

Deploys a new server using the specified parameters.



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/knife-cloudstack/connection.rb', line 113

def create_server(host_name, service_name, template_name, zone_name=nil, network_names=[])

  if host_name then
    if get_server(host_name) then
      puts "Error: Server '#{host_name}' already exists."
      exit 1
    end
  end

  #service = get_service_offering(service_name)
  #if !service then
  #  puts "Error: Service offering '#{service_name}' is invalid"
  #  exit 1
  #end

  #template = get_template(template_name)
  #if !template then
  #  puts "Error: Template '#{template_name}' is invalid"
  #  exit 1
  #end

  #zone = zone_name ? get_zone(zone_name) : get_default_zone
  #if !zone then
  #  msg = zone_name ? "Zone '#{zone_name}' is invalid" : "No default zone found"
  #  puts "Error: #{msg}"
  #  exit 1
  #end

  #networks = []
  #network_names.each do |name|
  #  network = get_network(name)
  #  if !network then
  #    puts "Error: Network '#{name}' not found"
  #    exit 1
  #  end
  #  networks << get_network(name)
  #end
  #if networks.empty? then
  #  networks << get_default_network
  #end
  #if networks.empty? then
  #  puts "No default network found"
  #  exit 1
  #end
  #network_ids = networks.map { |network|
  #  network['id']
  #}

  params = {
      'command' => 'deployVirtualMachine',
      'serviceOfferingId' => service_name,
      #'serviceOfferingId' => service['id'],
      'templateId' => template_name,
      #'templateId' => template['id'],
      'zoneId' => zone_name
      #'zoneId' => zone['id'],
      #'networkids' => network_ids.join(',')
  }
  params['name'] = host_name if host_name

  json = send_async_request(params)
  json['virtualmachine']
end

#delete_server(name) ⇒ Object

Deletes the server with the specified name.



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/knife-cloudstack/connection.rb', line 181

def delete_server(name)
  server = get_server(name)
  if !server || !server['id'] then
    puts "Error: Virtual machine '#{name}' does not exist"
    exit 1
  end

  params = {
      'command' => 'destroyVirtualMachine',
      'id' => server['id']
  }

  json = send_async_request(params)
  json['virtualmachine']
end

#disassociate_ip_address(id) ⇒ Object

Disassociates an ip address from the account.

Returns true if successful, false otherwise.



484
485
486
487
488
489
490
491
# File 'lib/knife-cloudstack/connection.rb', line 484

def disassociate_ip_address(id)
  params = {
      'command' => 'disassociateIpAddress',
      'id' => id
  }
  json = send_async_request(params)
  json['success']
end

#get_default_networkObject

Finds the default network.



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/knife-cloudstack/connection.rb', line 369

def get_default_network
  params = {
      'command' => 'listNetworks',
      'isDefault' => true
  }
  json = send_request(params)

  networks = json['network']
  return nil if !networks || networks.empty?

  default = networks.first
  return default if networks.length == 1

  networks.each { |n|
    if n['type'] == 'Direct' then
      default = n
      break
    end
  }

  default
end

#get_default_zoneObject

Finds the default zone for your account.



428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/knife-cloudstack/connection.rb', line 428

def get_default_zone
  params = {
      'command' => 'listZones',
      'available' => 'true'
  }
  json = send_request(params)

  zones = json['zone']
  return nil unless zones

  zones.first
end

#get_network(name) ⇒ Object

Finds the network with the specified name.



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/knife-cloudstack/connection.rb', line 348

def get_network(name)
  params = {
      'command' => 'listNetworks'
  }
  json = send_request(params)

  networks = json['network']
  return nil unless networks

  networks.each { |n|
    if n['name'] == name then
      return n
    end
  }

  nil
end

#get_public_ip_address(ip_address) ⇒ Object

Finds the public ip address for a given ip address string.



456
457
458
459
460
461
462
463
# File 'lib/knife-cloudstack/connection.rb', line 456

def get_public_ip_address(ip_address)
  params = {
      'command' => 'listPublicIpAddresses',
      'ipaddress' => ip_address
  }
  json = send_request(params)
  json['publicipaddress'].first
end

#get_server(name) ⇒ Object

Finds the server with the specified name.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/knife-cloudstack/connection.rb', line 44

def get_server(name)
  params = {
      'command' => 'listVirtualMachines',
      'name' => name
  }
  json = send_request(params)
  machines = json['virtualmachine']

  if !machines || machines.empty? then
    return nil
  end

  machines.first
end

#get_server_default_nic(server) ⇒ Object



93
94
95
96
97
# File 'lib/knife-cloudstack/connection.rb', line 93

def get_server_default_nic(server)
  server['nic'].each do |nic|
    return nic if nic['isdefault']
  end
end

#get_server_fqdn(server) ⇒ Object

Returns the fully qualified domain name for a server.



78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/knife-cloudstack/connection.rb', line 78

def get_server_fqdn(server)
  return nil unless server

  nic = get_server_default_nic(server) || {}
  networks = list_networks || {}

  id = nic['networkid']
  network = networks.select { |net|
    net['id'] == id
  }.first
  return nil unless network

  "#{server['name']}.#{network['networkdomain']}"
end

#get_server_public_ip(server, cached_rules = nil) ⇒ Object

Finds the public ip for a server



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/knife-cloudstack/connection.rb', line 62

def get_server_public_ip(server, cached_rules=nil)
  return nil unless server

  # find the public ip
  nic = get_server_default_nic(server) || {}
  if nic['type'] == 'Virtual' then
    ssh_rule = get_ssh_port_forwarding_rule(server, cached_rules)
    ssh_rule ? ssh_rule['ipaddress'] : nil
  else
    nic['ipaddress']
  end
end

#get_service_offering(name) ⇒ Object

Finds the service offering with the specified name.



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/knife-cloudstack/connection.rb', line 261

def get_service_offering(name)

  # TODO: use name parameter
  # listServiceOfferings in CloudStack 2.2 doesn't seem to work
  # when the name parameter is specified. When this is fixed,
  # the name parameter should be added to the request.
  params = {
      'command' => 'listServiceOfferings'
  }
  json = send_request(params)

  services = json['serviceoffering']
  return nil unless services

  services.each { |s|
    if s['name'] == name then
      return s
    end
  }

  nil
end

#get_ssh_port_forwarding_rule(server, cached_rules = nil) ⇒ Object

Gets the SSH port forwarding rule for the specified server.



508
509
510
511
512
513
514
515
# File 'lib/knife-cloudstack/connection.rb', line 508

def get_ssh_port_forwarding_rule(server, cached_rules=nil)
  rules = cached_rules || list_port_forwarding_rules || []
  rules.find_all { |r|
    r['virtualmachineid'] == server['id'] &&
        r['privateport'] == '22'&&
        r['publicport'] == '22'
  }.first
end

#get_template(name) ⇒ Object

Finds the template with the specified name.



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/knife-cloudstack/connection.rb', line 298

def get_template(name)

  # TODO: use name parameter
  # listTemplates in CloudStack 2.2 doesn't seem to work
  # when the name parameter is specified. When this is fixed,
  # the name parameter should be added to the request.
  params = {
      'command' => 'listTemplates',
      'templateFilter' => 'executable'
  }
  json = send_request(params)

  templates = json['template']
  if !templates then
    return nil
  end

  templates.each { |t|
    if t['name'] == name then
      return t
    end
  }

  nil
end

#get_zone(name) ⇒ Object

Finds the zone with the specified name.



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/knife-cloudstack/connection.rb', line 406

def get_zone(name)
  params = {
      'command' => 'listZones',
      'available' => 'true'
  }
  json = send_request(params)

  networks = json['zone']
  return nil unless networks

  networks.each { |z|
    if z['name'] == name then
      return z
    end
  }

  nil
end

#list_networksObject

Lists all available networks.



395
396
397
398
399
400
401
# File 'lib/knife-cloudstack/connection.rb', line 395

def list_networks
  params = {
      'command' => 'listNetworks'
  }
  json = send_request(params)
  json['network'] || []
end

#list_port_forwarding_rules(ip_address_id = nil) ⇒ Object

Lists all port forwarding rules.



496
497
498
499
500
501
502
503
# File 'lib/knife-cloudstack/connection.rb', line 496

def list_port_forwarding_rules(ip_address_id=nil)
  params = {
      'command' => 'listPortForwardingRules'
  }
  params['ipAddressId'] = ip_address_id if ip_address_id
  json = send_request(params)
  json['portforwardingrule']
end

#list_productsObject

Lists all the available products list in your account.



536
537
538
539
540
541
542
543
544
545
546
# File 'lib/knife-cloudstack/connection.rb', line 536

def list_products                        
  params = {                            
      'command' => 'listAvailableProductTypes'
  }
                                 
  json = send_request(params) 
  
  json["producttypes"] || [] 
    
  #json['virtualmachine'] || []          
end

#list_serversObject

Lists all the servers in your account.



102
103
104
105
106
107
108
# File 'lib/knife-cloudstack/connection.rb', line 102

def list_servers
  params = {
      'command' => 'listVirtualMachines'
  }
  json = send_request(params)
  json['virtualmachine'] || []
end

#list_service_offeringsObject

Lists all available service offerings.



287
288
289
290
291
292
293
# File 'lib/knife-cloudstack/connection.rb', line 287

def list_service_offerings
  params = {
      'command' => 'listServiceOfferings'
  }
  json = send_request(params)
  json['serviceoffering'] || []
end

#list_templates(filter) ⇒ Object

Lists all templates that match the specified filter.

Allowable filter values are:

  • featured - templates that are featured and are public

  • self - templates that have been registered/created by the owner

  • self-executable - templates that have been registered/created by the owner that can be used to deploy a new VM

  • executable - all templates that can be used to deploy a new VM

  • community - templates that are public



335
336
337
338
339
340
341
342
343
# File 'lib/knife-cloudstack/connection.rb', line 335

def list_templates(filter)
  filter ||= 'featured'
  params = {
      'command' => 'listTemplates',
      'templatefilter' => filter
  }
  json = send_request(params)
  json['template'] || []
end

#list_zonesObject

Lists all available zones.



444
445
446
447
448
449
450
451
# File 'lib/knife-cloudstack/connection.rb', line 444

def list_zones
  params = {
      'command' => 'listZones',
      'available' => 'true'
  }
  json = send_request(params)
  json['zone'] || []
end

#reboot_server(name) ⇒ Object

Reboot the server with the specified name.



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/knife-cloudstack/connection.rb', line 242

def reboot_server(name)
  server = get_server(name)
  if !server || !server['id'] then
    puts "Error: Virtual machine '#{name}' does not exist"
    exit 1
  end

  params = {
      'command' => 'rebootVirtualMachine',
      'id' => server['id']
  }

  json = send_async_request(params)
  json['virtualmachine']
end

#send_async_request(params) ⇒ Object

Sends an asynchronous request and waits for the response.

The contents of the ‘jobresult’ element are returned upon completion of the command.



598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
# File 'lib/knife-cloudstack/connection.rb', line 598

def send_async_request(params)

  json = send_request(params)
#puts json
  params = {
      'command' => 'queryAsyncJobResult',
      'jobId' => json['jobid']
  }

  max_tries = (ASYNC_TIMEOUT / ASYNC_POLL_INTERVAL).round
  max_tries.times do
    json = send_request(params)
    status = json['jobstatus']
#puts json
    print "."

    if status == 1 then
      return json['jobresult']
    elsif status == 2 then
      print "\n"
      puts "Request failed (#{json['jobresultcode']}): #{json['jobresult']}"
      exit 1
    end

    STDOUT.flush
    sleep ASYNC_POLL_INTERVAL
  end

  print "\n"
  puts "Error: Asynchronous request timed out"
  exit 1
end

#send_request(params) ⇒ Object

Sends a synchronous request to the CloudStack API and returns the response as a Hash.

The wrapper element of the response (e.g. mycommandresponse) is discarded and the contents of that element are returned.



555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
# File 'lib/knife-cloudstack/connection.rb', line 555

def send_request(params)
  params['response'] = 'json'
  params['apiKey'] = @api_key

  params_arr = []
  params.sort.each { |elem|
    params_arr << elem[0].to_s + '=' + elem[1].to_s
  }
  data = params_arr.join('&')
  encoded_data = URI.encode(data.downcase).gsub('+', '%20').gsub(',', '%2c')
  signature = OpenSSL::HMAC.digest('sha1', @secret_key, encoded_data)
  signature = Base64.encode64(signature).chomp
  signature = CGI.escape(signature)

  raw_url = "#{@api_url}?#{data}&signature=#{signature}"
  
#puts "request url : " + raw_url
  url = URI.parse(raw_url)

  http = Net::HTTP.new(url.host, url.port)
  
  http.use_ssl = (url.scheme == 'https')
  request = Net::HTTP::Get.new(url.to_s)
  response = http.request(request)

  #response = Net::HTTP.get_response(URI.parse(url))

  if !response.is_a?(Net::HTTPOK) then
    puts "Error #{response.code}: #{response.message}"
    puts JSON.pretty_generate(JSON.parse(response.body))
    puts "URL: #{url}"
    exit 1
  end

  json = JSON.parse(response.body)
  json[params['command'].downcase + 'response']
end

#start_server(name) ⇒ Object

Start the server with the specified name.



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/knife-cloudstack/connection.rb', line 222

def start_server(name)
  server = get_server(name)
  if !server || !server['id'] then
    puts "Error: Virtual machine '#{name}' does not exist"
    exit 1
  end

  params = {
      'command' => 'startVirtualMachine',
      'id' => server['id']
  }

  json = send_async_request(params)
  json['virtualmachine']
end

#stop_server(name, forced = nil) ⇒ Object

Stops the server with the specified name.



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/knife-cloudstack/connection.rb', line 201

def stop_server(name, forced=nil)
  server = get_server(name)
  if !server || !server['id'] then
    puts "Error: Virtual machine '#{name}' does not exist"
    exit 1
  end

  params = {
      'command' => 'stopVirtualMachine',
      'id' => server['id']
  }
  params['forced'] = true if forced

  json = send_async_request(params)
  json['virtualmachine']
end