summaryrefslogtreecommitdiffstats
path: root/lib/puppet/indirector/rest.rb
blob: d33150fc23f59cca20ee2e495abf07e4e5f056bd (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
require 'net/http'
require 'uri'

# Access objects via REST
class Puppet::Indirector::REST < Puppet::Indirector::Terminus

    def rest_connection_details
        { :host => Puppet[:server], :port => Puppet[:masterport].to_i }
    end

    def network_fetch(path)
        network {|conn| conn.get("/#{path}").body }
    end
    
    def network_delete(path)
        network {|conn| conn.delete("/#{path}").body }
    end
    
    def network_put(path, data)
        network {|conn| conn.put("/#{path}", data).body }
    end
    
    def find(request)
        network_result = network_fetch("#{indirection.name}/#{request.key}")
        raise YAML.load(network_result) if exception?(network_result)
        indirection.model.from_yaml(network_result)
    end
    
    def search(request)
        network_results = network_fetch("#{indirection.name}s/#{request.key}")
        raise YAML.load(network_results) if exception?(network_results)
        YAML.load(network_results.to_s).collect {|result| indirection.model.from_yaml(result) }
    end
    
    def destroy(request)
        network_result = network_delete("#{indirection.name}/#{request.key}")
        raise YAML.load(network_result) if exception?(network_result)
        YAML.load(network_result.to_s)      
    end
    
    def save(request)
        network_result = network_put("#{indirection.name}/", request.instance.to_yaml)
        raise YAML.load(network_result) if exception?(network_result)
        indirection.model.from_yaml(network_result)
    end
    
  private
  
    def network(&block)
        Net::HTTP.start(rest_connection_details[:host], rest_connection_details[:port]) {|conn| yield(conn) }
    end
  
    def exception?(yaml_string)
        yaml_string =~ %r{--- !ruby/exception}
    end
end