Class: WebHDFS::ClientV1

Inherits:
Object
  • Object
show all
Defined in:
lib/webhdfs/client_v1.rb

Direct Known Subclasses

Client

Constant Summary

OPT_TABLE =

This hash table holds command options.

{}
KNOWN_ERRORS =

internal use only

['LeaseExpiredException'].freeze
SSL_VERIFY_MODES =
[:none, :peer]
REDIRECTED_OPERATIONS =
['APPEND', 'CREATE', 'OPEN', 'GETFILECHECKSUM']

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host = 'localhost', port = 50070, username = nil, doas = nil, proxy_address = nil, proxy_port = nil, http_headers = {}) ⇒ ClientV1



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/webhdfs/client_v1.rb', line 40

def initialize(host='localhost', port=50070, username=nil, doas=nil, proxy_address=nil, proxy_port=nil, http_headers={})
  @host = host
  @port = port
  @username = username
  @doas = doas
  @proxy_address = proxy_address
  @proxy_port = proxy_port
  @retry_known_errors = false
  @retry_times = 1
  @retry_interval = 1

  @httpfs_mode = false

  @ssl = false
  @ssl_ca_file = nil
  @ssl_verify_mode = nil
  @ssl_cert = nil
  @ssl_key = nil
  @ssl_version = nil

  @kerberos = false
  @kerberos_keytab = nil
  @http_headers = http_headers
end

Instance Attribute Details

#doasObject

Returns the value of attribute doas



15
16
17
# File 'lib/webhdfs/client_v1.rb', line 15

def doas
  @doas
end

#hostObject

Returns the value of attribute host



15
16
17
# File 'lib/webhdfs/client_v1.rb', line 15

def host
  @host
end

#http_headersObject

Returns the value of attribute http_headers



30
31
32
# File 'lib/webhdfs/client_v1.rb', line 30

def http_headers
  @http_headers
end

#httpfs_modeObject

Returns the value of attribute httpfs_mode



19
20
21
# File 'lib/webhdfs/client_v1.rb', line 19

def httpfs_mode
  @httpfs_mode
end

#kerberosObject

Returns the value of attribute kerberos



29
30
31
# File 'lib/webhdfs/client_v1.rb', line 29

def kerberos
  @kerberos
end

#kerberos_keytabObject

Returns the value of attribute kerberos_keytab



29
30
31
# File 'lib/webhdfs/client_v1.rb', line 29

def kerberos_keytab
  @kerberos_keytab
end

#open_timeoutObject

default 30s (in ruby net/http)



17
18
19
# File 'lib/webhdfs/client_v1.rb', line 17

def open_timeout
  @open_timeout
end

#portObject

Returns the value of attribute port



15
16
17
# File 'lib/webhdfs/client_v1.rb', line 15

def port
  @port
end

#proxy_addressObject

Returns the value of attribute proxy_address



15
16
17
# File 'lib/webhdfs/client_v1.rb', line 15

def proxy_address
  @proxy_address
end

#proxy_passObject

Returns the value of attribute proxy_pass



16
17
18
# File 'lib/webhdfs/client_v1.rb', line 16

def proxy_pass
  @proxy_pass
end

#proxy_portObject

Returns the value of attribute proxy_port



15
16
17
# File 'lib/webhdfs/client_v1.rb', line 15

def proxy_port
  @proxy_port
end

#proxy_userObject

Returns the value of attribute proxy_user



16
17
18
# File 'lib/webhdfs/client_v1.rb', line 16

def proxy_user
  @proxy_user
end

#read_timeoutObject

default 60s (in ruby net/http)



18
19
20
# File 'lib/webhdfs/client_v1.rb', line 18

def read_timeout
  @read_timeout
end

#retry_intervalObject

default 1 ([sec], ignored when retry_known_errors is false)



22
23
24
# File 'lib/webhdfs/client_v1.rb', line 22

def retry_interval
  @retry_interval
end

#retry_known_errorsObject

default false (not to retry)



20
21
22
# File 'lib/webhdfs/client_v1.rb', line 20

def retry_known_errors
  @retry_known_errors
end

#retry_timesObject

default 1 (ignored when retry_known_errors is false)



21
22
23
# File 'lib/webhdfs/client_v1.rb', line 21

def retry_times
  @retry_times
end

#sslObject

Returns the value of attribute ssl



23
24
25
# File 'lib/webhdfs/client_v1.rb', line 23

def ssl
  @ssl
end

#ssl_ca_fileObject

Returns the value of attribute ssl_ca_file



24
25
26
# File 'lib/webhdfs/client_v1.rb', line 24

def ssl_ca_file
  @ssl_ca_file
end

#ssl_certObject

Returns the value of attribute ssl_cert



26
27
28
# File 'lib/webhdfs/client_v1.rb', line 26

def ssl_cert
  @ssl_cert
end

#ssl_keyObject

Returns the value of attribute ssl_key



27
28
29
# File 'lib/webhdfs/client_v1.rb', line 27

def ssl_key
  @ssl_key
end

#ssl_verify_modeObject

Returns the value of attribute ssl_verify_mode



25
26
27
# File 'lib/webhdfs/client_v1.rb', line 25

def ssl_verify_mode
  @ssl_verify_mode
end

#ssl_versionObject

Returns the value of attribute ssl_version



28
29
30
# File 'lib/webhdfs/client_v1.rb', line 28

def ssl_version
  @ssl_version
end

#usernameObject

Returns the value of attribute username



15
16
17
# File 'lib/webhdfs/client_v1.rb', line 15

def username
  @username
end

Instance Method Details

#api_path(path) ⇒ Object



234
235
236
237
238
239
240
# File 'lib/webhdfs/client_v1.rb', line 234

def api_path(path)
  if path.start_with?('/')
    '/webhdfs/v1' + path
  else
    '/webhdfs/v1/' + path
  end
end

#append(path, body, options = {}) ⇒ Object

curl -i -X POST “



79
80
81
82
83
84
85
86
# File 'lib/webhdfs/client_v1.rb', line 79

def append(path, body, options={})
  if @httpfs_mode
    options = options.merge({'data' => 'true'})
  end
  check_options(options, OPT_TABLE['APPEND'])
  res = operate_requests('POST', path, 'APPEND', options, body)
  res.code == '200'
end

#build_path(path, op, params) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/webhdfs/client_v1.rb', line 242

def build_path(path, op, params)
  opts = if @username and @doas
           {'op' => op, 'user.name' => @username, 'doas' => @doas}
         elsif @username
           {'op' => op, 'user.name' => @username}
         elsif @doas
           {'op' => op, 'doas' => @doas}
         else
           {'op' => op}
         end
  query = URI.encode_www_form(params.merge(opts))
  api_path(path) + '?' + query
end

#check_options(options, optdecl = []) ⇒ Object

def delegation_token(user, options={}) # GETDELEGATIONTOKEN

raise NotImplementedError

end def renew_delegation_token(token, options={}) # RENEWDELEGATIONTOKEN

raise NotImplementedError

end def cancel_delegation_token(token, options={}) # CANCELDELEGATIONTOKEN

raise NotImplementedError

end

Raises:

  • (ArgumentError)


225
226
227
228
# File 'lib/webhdfs/client_v1.rb', line 225

def check_options(options, optdecl=[])
  ex = options.keys.map(&:to_s) - (optdecl || [])
  raise ArgumentError, "no such option: #{ex.join(' ')}" unless ex.empty?
end

#check_success_json(res, attr = nil) ⇒ Object



230
231
232
# File 'lib/webhdfs/client_v1.rb', line 230

def check_success_json(res, attr=nil)
  res.code == '200' and res.content_type == 'application/json' and (attr.nil? or JSON.parse(res.body)[attr])
end

#checksum(path, options = {}) ⇒ Object Also known as: getfilechecksum



152
153
154
155
156
# File 'lib/webhdfs/client_v1.rb', line 152

def checksum(path, options={})
  check_options(options, OPT_TABLE['GETFILECHECKSUM'])
  res = operate_requests('GET', path, 'GETFILECHECKSUM', options)
  check_success_json(res, 'FileChecksum')
end

#content_summary(path, options = {}) ⇒ Object Also known as: getcontentsummary



144
145
146
147
148
# File 'lib/webhdfs/client_v1.rb', line 144

def content_summary(path, options={})
  check_options(options, OPT_TABLE['GETCONTENTSUMMARY'])
  res = operate_requests('GET', path, 'GETCONTENTSUMMARY', options)
  check_success_json(res, 'ContentSummary')
end

#homedir(options = {}) ⇒ Object Also known as: gethomedirectory



160
161
162
163
164
# File 'lib/webhdfs/client_v1.rb', line 160

def homedir(options={})
  check_options(options, OPT_TABLE['GETHOMEDIRECTORY'])
  res = operate_requests('GET', '/', 'GETHOMEDIRECTORY', options)
  check_success_json(res, 'Path')
end

#list(path, options = {}) ⇒ Object Also known as: liststatus



136
137
138
139
140
# File 'lib/webhdfs/client_v1.rb', line 136

def list(path, options={})
  check_options(options, OPT_TABLE['LISTSTATUS'])
  res = operate_requests('GET', path, 'LISTSTATUS', options)
  check_success_json(res, 'FileStatuses')['FileStatus']
end

#mkdir(path, options = {}) ⇒ Object Also known as: mkdirs



100
101
102
103
104
# File 'lib/webhdfs/client_v1.rb', line 100

def mkdir(path, options={})
  check_options(options, OPT_TABLE['MKDIRS'])
  res = operate_requests('PUT', path, 'MKDIRS', options)
  check_success_json(res, 'boolean')
end

#operate_requests(method, path, op, params = {}, payload = nil) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/webhdfs/client_v1.rb', line 257

def operate_requests(method, path, op, params={}, payload=nil)
  if not @httpfs_mode and REDIRECTED_OPERATIONS.include?(op)
    res = request(@host, @port, method, path, op, params, nil)
    unless res.is_a?(Net::HTTPRedirection) and res['location']
      msg = "NameNode returns non-redirection (or without location header), code:#{res.code}, body:#{res.body}."
      raise WebHDFS::RequestFailedError, msg
    end
    uri = URI.parse(res['location'])
    rpath = if uri.query
              uri.path + '?' + uri.query
            else
              uri.path
            end
    request(uri.host, uri.port, method, rpath, nil, {}, payload, {'Content-Type' => 'application/octet-stream'})
  else
    if @httpfs_mode and not payload.nil?
      request(@host, @port, method, path, op, params, payload, {'Content-Type' => 'application/octet-stream'})
    else
      request(@host, @port, method, path, op, params, payload)
    end
  end
end

#rename(path, dest, options = {}) ⇒ Object

curl -i -X PUT “<HOST>:<PORT>/webhdfs/v1/<PATH>?op=RENAME&destination=<PATH>”



109
110
111
112
113
114
115
116
# File 'lib/webhdfs/client_v1.rb', line 109

def rename(path, dest, options={})
  check_options(options, OPT_TABLE['RENAME'])
  unless dest.start_with?('/')
    dest = '/' + dest
  end
  res = operate_requests('PUT', path, 'RENAME', options.merge({'destination' => dest}))
  check_success_json(res, 'boolean')
end

#request(host, port, method, path, op = nil, params = {}, payload = nil, header = nil, retries = 0) ⇒ Object

IllegalArgumentException 400 Bad Request UnsupportedOperationException 400 Bad Request SecurityException 401 Unauthorized IOException 403 Forbidden FileNotFoundException 404 Not Found RumtimeException 500 Internal Server Error



286
287
288
289
290
291
292
293
294
295
296
297
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/webhdfs/client_v1.rb', line 286

def request(host, port, method, path, op=nil, params={}, payload=nil, header=nil, retries=0)
  conn = Net::HTTP.new(host, port, @proxy_address, @proxy_port)
  conn.proxy_user = @proxy_user if @proxy_user
  conn.proxy_pass = @proxy_pass if @proxy_pass
  conn.open_timeout = @open_timeout if @open_timeout
  conn.read_timeout = @read_timeout if @read_timeout

  path = Addressable::URI.escape(path) # make path safe for transmission via HTTP
  request_path = if op
                   build_path(path, op, params)
                 else
                   path
                 end
  if @ssl
    conn.use_ssl = true
    conn.ca_file = @ssl_ca_file if @ssl_ca_file
    if @ssl_verify_mode
      require 'openssl'
      conn.verify_mode = case @ssl_verify_mode
                         when :none then OpenSSL::SSL::VERIFY_NONE
                         when :peer then OpenSSL::SSL::VERIFY_PEER
                         end
    end
    conn.cert = @ssl_cert if @ssl_cert
    conn.key = @ssl_key if @ssl_key
    conn.ssl_version = @ssl_version if @ssl_version
  end

  gsscli = nil
  if @kerberos
    require 'base64'
    require 'gssapi'
    gsscli = GSSAPI::Simple.new(@host, 'HTTP', @kerberos_keytab)
    token = nil
    begin
      token = gsscli.init_context
    rescue => e
      raise WebHDFS::KerberosError, e.message
    end
    if header
      header['Authorization'] = "Negotiate #{Base64.strict_encode64(token)}"
    else
      header = {'Authorization' => "Negotiate #{Base64.strict_encode64(token)}"}
    end
  else
    header = {} if header.nil?
    header = @http_headers.merge(header)
  end

  res = nil
  if !payload.nil? and payload.respond_to? :read and payload.respond_to? :size
    req = Net::HTTPGenericRequest.new(method,(payload ? true : false),true,request_path,header)
    raise WebHDFS::ClientError, 'Error accepting given IO resource as data payload, Not valid in methods other than PUT and POST' unless (method == 'PUT' or method == 'POST')

    req.body_stream = payload
    req.content_length = payload.size
    begin
      res = conn.request(req)
    rescue => e
      raise WebHDFS::ServerError, "Failed to connect to host #{host}:#{port}, #{e.message}"
    end
  else
    begin
      res = conn.send_request(method, request_path, payload, header)
    rescue => e
      raise WebHDFS::ServerError, "Failed to connect to host #{host}:#{port}, #{e.message}"
    end
  end

  if @kerberos and res.code == '307'
    itok = (res.header.get_fields('WWW-Authenticate') || ['']).pop.split(/\s+/).last
    unless itok
      raise WebHDFS::KerberosError, 'Server does not return WWW-Authenticate header'
    end

    begin
      gsscli.init_context(Base64.strict_decode64(itok))
    rescue => e
      raise WebHDFS::KerberosError, e.message
    end
  end

  case res
  when Net::HTTPSuccess
    res
  when Net::HTTPRedirection
    res
  else
    message = if res.body and not res.body.empty?
                res.body.gsub(/\n/, '')
              else
                'Response body is empty...'
              end

    if @retry_known_errors && retries < @retry_times
      detail = nil
      if message =~ /^\{"RemoteException":\{/
        begin
          detail = JSON.parse(message)
        rescue
          # ignore broken json response body
        end
      end
      if detail && detail['RemoteException'] && KNOWN_ERRORS.include?(detail['RemoteException']['exception'])
        sleep @retry_interval if @retry_interval > 0
        return request(host, port, method, path, op, params, payload, header, retries+1)
      end
    end

    case res.code
    when '400'
      raise WebHDFS::ClientError, message
    when '401'
      raise WebHDFS::SecurityError, message
    when '403'
      raise WebHDFS::IOError, message
    when '404'
      raise WebHDFS::FileNotFoundError, message
    when '500'
      raise WebHDFS::ServerError, message
    else
      raise WebHDFS::RequestFailedError, "response code:#{res.code}, message:#{message}"
    end
  end
end