Class: Puppet::Indirector::REST

Inherits:
Terminus show all
Defined in:
lib/puppet/indirector/rest.rb

Overview

Access objects via REST

Constant Summary collapse

IndirectedRoutes =
Puppet::Network::HTTP::API::IndirectedRoutes
EXCLUDED_FORMATS =
[:yaml, :b64_zlib_yaml, :dot]
MAJOR_VERSION_JSON_DEFAULT =

puppet major version where JSON is enabled by default

5

Constants included from Util

Util::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE

Constants included from Util::POSIX

Util::POSIX::LOCALE_ENV_VARS, Util::POSIX::USER_ENV_VARS

Constants included from Util::SymbolicFileMode

Util::SymbolicFileMode::SetGIDBit, Util::SymbolicFileMode::SetUIDBit, Util::SymbolicFileMode::StickyBit, Util::SymbolicFileMode::SymbolicMode, Util::SymbolicFileMode::SymbolicSpecialToBit

Constants included from Util::Docs

Util::Docs::HEADER_LEVELS

Class Attribute Summary collapse

Attributes included from Util::Docs

#doc, #nodoc

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Terminus

abstract_terminus?, #allow_remote_requests?, const2name, #indirection, indirection_name, inherited, #initialize, mark_as_abstract_terminus, model, #model, #name, name2const, register_terminus_class, terminus_class, terminus_classes, #terminus_type, #validate, #validate_model

Methods included from Util::InstanceLoader

#instance_docs, #instance_hash, #instance_load, #instance_loader, #instance_loading?, #loaded_instance, #loaded_instances

Methods included from Util

absolute_path?, benchmark, chuser, clear_environment, default_env, deterministic_rand, deterministic_rand_int, exit_on_fail, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, safe_posix_fork, set_env, symbolizehash, thinmark, uri_encode, uri_query_encode, uri_to_path, which, withenv, withumask

Methods included from Util::POSIX

#get_posix_field, #gid, #idfield, #methodbyid, #methodbyname, #search_posix_field, #uid

Methods included from Util::SymbolicFileMode

#normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Methods included from Util::Docs

#desc, #dochook, #doctable, #markdown_definitionlist, #markdown_header, #nodoc?, #pad, scrub

Constructor Details

This class inherits a constructor from Puppet::Indirector::Terminus

Class Attribute Details

.port_settingObject (readonly)

Returns the value of attribute port_setting.



20
21
22
# File 'lib/puppet/indirector/rest.rb', line 20

def port_setting
  @port_setting
end

.server_settingObject (readonly)

Returns the value of attribute server_setting.



20
21
22
# File 'lib/puppet/indirector/rest.rb', line 20

def server_setting
  @server_setting
end

Class Method Details

.portObject

For port there’s a little bit of an extra snag: setting a specific server setting and relying on the default port for that server is common, so we also want to check if the assocaited SERVER setting has been set by the user. If either of those are set we ignore the failover-selected port.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/puppet/indirector/rest.rb', line 80

def self.port
  setting = port_setting()
  srv_setting = server_setting()
  if (setting && setting != :masterport && Puppet.settings.set_by_config?(setting)) ||
     (srv_setting && srv_setting != :server && Puppet.settings.set_by_config?(srv_setting))
    Puppet.settings[setting].to_i
  else
    begin
      Puppet.lookup(:serverport).to_i
    rescue
      if primary_server = Puppet.settings[:server_list][0]
        Puppet.debug "Dynamically-bound port lookup failed; using first entry"

        # Port might not be set, so we want to fallback in that
        # case. We know we don't need to use `setting` here, since
        # the default value of every port setting is `masterport`
        (primary_server[1] || Puppet.settings[:masterport]).to_i
      else
        setting ||= :masterport
        Puppet.debug "Dynamically-bound port lookup failed; falling back to #{setting} setting"
        Puppet.settings[setting].to_i
      end
    end
  end
end

.serverObject

The logic for server and port is kind of gross. In summary: IF an endpoint-specific setting is requested AND that setting has been set by the user

Use that setting.
     The defaults for these settings are the "normal" server/masterport settings, so
     when they are unset we instead want to "fall back" to the failover-selected
     host/port pair.

ELSE IF we have a failover-selected host/port

Use what the failover logic came up with

ELSE IF the server_list setting is in use

Use the first entry - failover hasn't happened yet, but that
setting is still authoritative

ELSE

Go for the legacy server/masterport settings, and hope for the best


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/puppet/indirector/rest.rb', line 55

def self.server
  setting = server_setting()
  if setting && setting != :server && Puppet.settings.set_by_config?(setting)
    Puppet.settings[setting]
  else
    begin
      Puppet.lookup(:server)
    rescue
      if primary_server = Puppet.settings[:server_list][0]
        Puppet.debug "Dynamically-bound server lookup failed; using first entry"
        primary_server[0]
      else
        setting ||= :server
        Puppet.debug "Dynamically-bound server lookup failed, falling back to #{setting} setting"
        Puppet.settings[setting]
      end
    end
  end
end

.srv_serviceObject



38
39
40
# File 'lib/puppet/indirector/rest.rb', line 38

def self.srv_service
  @srv_service || :puppet
end

.use_port_setting(setting) ⇒ Object

Specify the setting that we should use to get the port.



29
30
31
# File 'lib/puppet/indirector/rest.rb', line 29

def self.use_port_setting(setting)
  @port_setting = setting
end

.use_server_setting(setting) ⇒ Object

Specify the setting that we should use to get the server name.



24
25
26
# File 'lib/puppet/indirector/rest.rb', line 24

def self.use_server_setting(setting)
  @server_setting = setting
end

.use_srv_service(service) ⇒ Object

Specify the service to use when doing SRV record lookup



34
35
36
# File 'lib/puppet/indirector/rest.rb', line 34

def self.use_srv_service(service)
  @srv_service = service
end

Instance Method Details

#add_profiling_header(headers) ⇒ Object



119
120
121
122
123
124
# File 'lib/puppet/indirector/rest.rb', line 119

def add_profiling_header(headers)
  if (Puppet[:profile])
    headers[Puppet::Network::HTTP::HEADER_ENABLE_PROFILING] = "true"
  end
  headers
end

#destroy(request) ⇒ Object

Raises:

  • (ArgumentError)


219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/puppet/indirector/rest.rb', line 219

def destroy(request)
  raise ArgumentError, _("DELETE does not accept options") unless request.options.empty?

  response = do_request(request) do |req|
    http_delete(req, IndirectedRoutes.request_to_uri(req), headers)
  end

  if is_http_200?(response)
    content_type, body = parse_response(response)
    deserialize_destroy(content_type, body)
  else
    nil
  end
end

#do_request(request) ⇒ Object

Encapsulate call to request.do_request with the arguments from this class Then yield to the code block that was called in We certainly could have retained the full request.do_request(…) { |r| … } but this makes the code much cleaner and we only then actually make the call to request.do_request from here, thus if we change what we pass or how we get it, we only need to change it here.



255
256
257
258
259
260
261
# File 'lib/puppet/indirector/rest.rb', line 255

def do_request(request)
  response = request.do_request(self.class.srv_service, self.class.server, self.class.port) { |req| yield(req) }

  handle_response(request, response) if response

  response
end

#find(request) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/puppet/indirector/rest.rb', line 156

def find(request)
  uri, body = IndirectedRoutes.request_to_uri_and_body(request)
  uri_with_query_string = "#{uri}?#{body}"

  response = do_request(request) do |req|
    # WEBrick in Ruby 1.9.1 only supports up to 1024 character lines in an HTTP request
    # http://redmine.ruby-lang.org/issues/show/3991
    if "GET #{uri_with_query_string} HTTP/1.1\r\n".length > 1024
      uri_with_env = "#{uri}?environment=#{request.environment.name}"
      http_post(req, uri_with_env, body, headers)
    else
      http_get(req, uri_with_query_string, headers)
    end
  end

  if is_http_200?(response)
    content_type, body = parse_response(response)
    result = deserialize_find(content_type, body)
    result.name = request.key if result.respond_to?(:name=)
    result

  elsif is_http_404?(response)
    return nil unless request.options[:fail_on_404]

    # 404 can get special treatment as the indirector API can not produce a meaningful
    # reason to why something is not found - it may not be the thing the user is
    # expecting to find that is missing, but something else (like the environment).
    # While this way of handling the issue is not perfect, there is at least an error
    # that makes a user aware of the reason for the failure.
    #
    content_type, body = parse_response(response)
    msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(uri_with_query_string, 100), body: body }
    raise Puppet::Error, msg
  else
    nil
  end
end

#handle_response(request, response) ⇒ Object



263
264
265
266
267
268
269
270
271
# File 'lib/puppet/indirector/rest.rb', line 263

def handle_response(request, response)
  server_version = response[Puppet::Network::HTTP::HEADER_PUPPET_VERSION]
  if server_version &&
     SemanticPuppet::Version.parse(server_version).major < MAJOR_VERSION_JSON_DEFAULT &&
     Puppet[:preferred_serialization_format] != 'pson'
    Puppet.warning("Downgrading to PSON for future requests")
    Puppet[:preferred_serialization_format] = 'pson'
  end
end

#head(request) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
# File 'lib/puppet/indirector/rest.rb', line 194

def head(request)
  response = do_request(request) do |req|
    http_head(req, IndirectedRoutes.request_to_uri(req), headers)
  end

  if is_http_200?(response)
    true
  else
    false
  end
end

#headersObject

Provide appropriate headers.



107
108
109
110
111
112
113
114
115
116
117
# File 'lib/puppet/indirector/rest.rb', line 107

def headers
  # yaml is not allowed on the network
  network_formats = model.supported_formats - EXCLUDED_FORMATS
  mime_types = network_formats.map { |f| model.get_format(f).mime }
  common_headers = {
    "Accept"                                     => mime_types.join(', '),
    Puppet::Network::HTTP::HEADER_PUPPET_VERSION => Puppet.version
  }

  add_accept_encoding(common_headers)
end

#http_delete(request, path, headers = nil, *args) ⇒ Object



143
144
145
# File 'lib/puppet/indirector/rest.rb', line 143

def http_delete(request, path, headers = nil, *args)
  http_request(:delete, request, path, add_profiling_header(headers), *args)
end

#http_get(request, path, headers = nil, *args) ⇒ Object



131
132
133
# File 'lib/puppet/indirector/rest.rb', line 131

def http_get(request, path, headers = nil, *args)
  http_request(:get, request, path, add_profiling_header(headers), *args)
end

#http_head(request, path, headers = nil, *args) ⇒ Object



139
140
141
# File 'lib/puppet/indirector/rest.rb', line 139

def http_head(request, path, headers = nil, *args)
  http_request(:head, request, path, add_profiling_header(headers), *args)
end

#http_post(request, path, data, headers = nil, *args) ⇒ Object



135
136
137
# File 'lib/puppet/indirector/rest.rb', line 135

def http_post(request, path, data, headers = nil, *args)
  http_request(:post, request, path, data, add_profiling_header(headers), *args)
end

#http_put(request, path, data, headers = nil, *args) ⇒ Object



147
148
149
# File 'lib/puppet/indirector/rest.rb', line 147

def http_put(request, path, data, headers = nil, *args)
  http_request(:put, request, path, data, add_profiling_header(headers), *args)
end

#http_request(method, request, *args) ⇒ Object



151
152
153
154
# File 'lib/puppet/indirector/rest.rb', line 151

def http_request(method, request, *args)
  conn = network(request)
  conn.send(method, *args)
end

#network(request) ⇒ Object



126
127
128
129
# File 'lib/puppet/indirector/rest.rb', line 126

def network(request)
  Puppet::Network::HttpPool.http_instance(request.server || self.class.server,
                                          request.port || self.class.port)
end

#save(request) ⇒ Object

Raises:

  • (ArgumentError)


234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/puppet/indirector/rest.rb', line 234

def save(request)
  raise ArgumentError, _("PUT does not accept options") unless request.options.empty?

  response = do_request(request) do |req|
    http_put(req, IndirectedRoutes.request_to_uri(req), req.instance.render, headers.merge({ "Content-Type" => req.instance.mime }))
  end

  if is_http_200?(response)
    content_type, body = parse_response(response)
    deserialize_save(content_type, body)
  else
    nil
  end
end

#search(request) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/puppet/indirector/rest.rb', line 206

def search(request)
  response = do_request(request) do |req|
    http_get(req, IndirectedRoutes.request_to_uri(req), headers)
  end

  if is_http_200?(response)
    content_type, body = parse_response(response)
    deserialize_search(content_type, body) || []
  else
    []
  end
end

#validate_key(request) ⇒ Object



273
274
275
# File 'lib/puppet/indirector/rest.rb', line 273

def validate_key(request)
  # Validation happens on the remote end
end