Module: PuppetX::Snap::API

Defined in:
lib/puppet_x/snap/api.rb

Class Method Summary collapse

Class Method Details

.call_api(request) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/puppet_x/snap/api.rb', line 25

def call_api(request)
  client = ::NetX::HTTPUnix.new('unix:///run/snapd.socket')

  response = nil
  retried = 0
  max_retries = 5
  # Read timeout can happen while installing core snap. The snap daemon briefly restarts
  # which drops the connection to the socket.
  loop do
    response = client.request(request)
    break unless response.is_a?(Net::HTTPContinue)
  rescue Net::ReadTimeout, Net::OpenTimeout
    raise Puppet::Error, "Got timeout wile calling the api #{retried} times! Giving up..." if retried > max_retries

    Puppet.debug('Got timeout while calling the api, retrying...')
    retried += 1
    retry
  end

  JSON.parse(response.body)
end

.complete(id) ⇒ Object

Queries the API for a specific change and waits until it has been completed.

Parameters:

  • id

    The change ID to search for.



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/puppet_x/snap/api.rb', line 66

def complete(id)
  completed = false
  until completed
    res = get_status(id)
    case res['result']['status']
    when 'Do', 'Doing', 'Undoing', 'Undo'
      # Still running
      # Wait a little bit before hitting the API again!
      sleep(1)
      next
    when 'Abort', 'Hold', 'Error'
      raise Puppet::Error, "Error while executing the request #{res}"
    when 'Done'
      completed = true
    else
      raise Puppet::Error, "Unknown status #{res}"
    end
  end
end

.get_id_from_async_req(request) ⇒ Object

Helper method to return the change ID from a asynchronous request response.

Raises:

  • (Puppet::Error)


48
49
50
51
52
53
# File 'lib/puppet_x/snap/api.rb', line 48

def get_id_from_async_req(request)
  # If the request failed raise an error
  raise Puppet::Error, "Request failed with #{request['result']['message']}" if request['type'] == 'error'

  request['change']
end

.get_status(id) ⇒ Object

Get the status of a change

Parameters:

  • id

    The change ID to search for.



58
59
60
# File 'lib/puppet_x/snap/api.rb', line 58

def get_status(id)
  get("/v2/changes/#{id}")
end