summaryrefslogtreecommitdiffstats
path: root/lib/puppet/indirector/rest.rb
blob: c33b8a9497e640f3d1cdaff746f6a8afb0b92a0e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
require 'net/http'
require 'uri'

# Access objects via REST
class Puppet::Indirector::REST < Puppet::Indirector::Terminus
    # Figure out the content type, turn that into a format, and use the format
    # to extract the body of the response.
    def deserialize(response, multiple = false)
        case response.code
        when "404"
            return nil
        when /^2/
            unless response['content-type']
                raise "No content type in http response; cannot parse"
            end

            # Convert the response to a deserialized object.
            if multiple
                model.convert_from_multiple(response['content-type'], response.body)
            else
                model.convert_from(response['content-type'], response.body)
            end
        else
            # Raise the http error if we didn't get a 'success' of some kind.
            message = "Server returned %s: %s" % [response.code, response.message]
            raise Net::HTTPError.new(message, response)
        end
    end

    # Provide appropriate headers.
    def headers
        {"Accept" => model.supported_formats.join(", ")}
    end
  
    def network
        Puppet::Network::HttpPool.http_instance(Puppet[:server], Puppet[:masterport].to_i)
    end

    def rest_connection_details
        { :host => Puppet[:server], :port => Puppet[:masterport].to_i }
    end
    
    def find(request)
        deserialize network.get("/#{indirection.name}/#{request.key}", headers)
    end
    
    def search(request)
        if request.key
            path = "/#{indirection.name}s/#{request.key}"
        else
            path = "/#{indirection.name}s"
        end
        deserialize(network.get(path, headers), true)
    end
    
    def destroy(request)
        deserialize network.delete("/#{indirection.name}/#{request.key}", headers)
    end
    
    def save(request)
        deserialize network.put("/#{indirection.name}/", request.instance.render, headers)
    end
end