Class: TreasureData::API

Inherits:
Object
  • Object
show all
Defined in:
lib/td/client/api.rb

Defined Under Namespace

Modules: DeflateReadBodyMixin, DirectReadBodyMixin

Constant Summary collapse

DEFAULT_ENDPOINT =
'api.treasure-data.com'
DEFAULT_IMPORT_ENDPOINT =
'api-import.treasure-data.com'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(apikey, opts = {}) ⇒ API

Returns a new instance of API.



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
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/td/client/api.rb', line 23

def initialize(apikey, opts={})
  require 'json'
  require 'time'
  require 'uri'
  require 'net/http'
  require 'net/https'
  require 'time'

  @apikey = apikey
  @user_agent = "TD-Client-Ruby: #{TreasureData::Client::VERSION}"
  @user_agent = "#{opts[:user_agent]}; " + @user_agent if opts.has_key?(:user_agent)

  endpoint = opts[:endpoint] || ENV['TD_API_SERVER'] || DEFAULT_ENDPOINT
  uri = URI.parse(endpoint)

  case uri.scheme
  when 'http', 'https'
    @host = uri.host
    @port = uri.port
    @ssl = uri.scheme == 'https'
    @base_path = uri.path.to_s

  else
    if uri.port
      # invalid URI
      raise "Invalid endpoint: #{endpoint}"
    end

    # generic URI
    @host, @port = endpoint.split(':', 2)
    @port = @port.to_i
    if opts[:ssl]
      @port = 443 if @port == 0
      @ssl = true
    else
      @port = 80 if @port == 0
      @ssl = false
    end
    @base_path = ''
  end

  @http_proxy = opts[:http_proxy] || ENV['HTTP_PROXY']
  if @http_proxy
    if @http_proxy =~ /\Ahttp:\/\/(.*)\z/
      @http_proxy = $~[1]
    end
    proxy_host, proxy_port = @http_proxy.split(':',2)
    proxy_port = (proxy_port ? proxy_port.to_i : 80)
    @http_class = Net::HTTP::Proxy(proxy_host, proxy_port)
  else
    @http_class = Net::HTTP
  end
end

Instance Attribute Details

#apikeyObject (readonly)

TODO error check & raise appropriate errors



79
80
81
# File 'lib/td/client/api.rb', line 79

def apikey
  @apikey
end

Class Method Details

.normalize_database_name(name) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/td/client/api.rb', line 126

def self.normalize_database_name(name)
  name = name.to_s
  if name.empty?
    raise "Empty name is not allowed"
  end
  if name.length < 3
    name += "_"*(3-name.length)
  end
  if 256 < name.length
    name = name[0,254]+"__"
  end
  name = name.downcase
  name = name.gsub(/[^a-z0-9_]/, '_')
  name
end

.normalize_table_name(name) ⇒ Object



142
143
144
# File 'lib/td/client/api.rb', line 142

def self.normalize_table_name(name)
  normalize_database_name(name)
end

.normalize_type_name(name) ⇒ Object

TODO support array types



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/td/client/api.rb', line 147

def self.normalize_type_name(name)
  case name
  when /int/i, /integer/i
    "int"
  when /long/i, /bigint/i
    "long"
  when /string/i
    "string"
  when /float/i
    "float"
  when /double/i
    "double"
  else
    raise "Type name must eather of int, long, string float or double"
  end
end

.normalized_msgpack(record, out = nil) ⇒ Object



81
82
83
84
85
86
87
88
89
# File 'lib/td/client/api.rb', line 81

def self.normalized_msgpack(record, out = nil)
  record.keys.each { |k|
    v = record[k]
    if v.kind_of?(Bignum)
      record[k] = v.to_s
    end
  }
  record.to_msgpack(out)
end

.validate_column_name(name) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/td/client/api.rb', line 113

def self.validate_column_name(name)
  name = name.to_s
  if name.empty?
    raise "Empty column name is not allowed"
  end
  if 256 < name.length
    raise "Column name must be to 256 characters, got #{name.length} characters."
  end
  unless name =~ /^([a-z0-9_]+)$/
    raise "Column name must consist only of alphabets, numbers, '_'."
  end
end

.validate_database_name(name) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/td/client/api.rb', line 91

def self.validate_database_name(name)
  name = name.to_s
  if name.empty?
    raise "Empty name is not allowed"
  end
  if name.length < 3 || 256 < name.length
    raise "Name must be 3 to 256 characters, got #{name.length} characters."
  end
  unless name =~ /^([a-z0-9_]+)$/
    raise "Name must consist only of lower-case alphabets, numbers and '_'."
  end
  name
end

.validate_result_set_name(name) ⇒ Object



109
110
111
# File 'lib/td/client/api.rb', line 109

def self.validate_result_set_name(name)
  validate_database_name(name)
end

.validate_table_name(name) ⇒ Object



105
106
107
# File 'lib/td/client/api.rb', line 105

def self.validate_table_name(name)
  validate_database_name(name)
end

Instance Method Details

#account_core_utilization(from, to) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/td/client/api.rb', line 185

def (from, to)
  params = { }
  params['from'] = from.to_s if from
  params['to'] = to.to_s if to
  code, body, res = get("/v3/account/core_utilization", params)
  if code != "200"
    raise_error("Show account failed", res)
  end
  js = checked_json(body, %w[from to interval history])
  from = Time.parse(js['from']).utc
  to = Time.parse(js['to']).utc
  interval = js['interval'].to_i
  history = js['history']
  return [from, to, interval, history]
end

#add_apikey(user) ⇒ Object

> true



1165
1166
1167
1168
1169
1170
1171
# File 'lib/td/client/api.rb', line 1165

def add_apikey(user)
  code, body, res = post("/v3/user/apikey/add/#{e user}")
  if code != "200"
    raise_error("Adding API key failed", res)
  end
  return true
end

#add_user(name, org, email, password) ⇒ Object

> true



1126
1127
1128
1129
1130
1131
1132
1133
# File 'lib/td/client/api.rb', line 1126

def add_user(name, org, email, password)
  params = {'organization'=>org, :email=>email, :password=>password}
  code, body, res = post("/v3/user/add/#{e name}", params)
  if code != "200"
    raise_error("Adding user failed", res)
  end
  return true
end

#authenticate(user, password) ⇒ Object

apikey:String



1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
# File 'lib/td/client/api.rb', line 1094

def authenticate(user, password)
  code, body, res = post("/v3/user/authenticate", {'user'=>user, 'password'=>password})
  if code != "200"
    if code == "400"
      raise_error("Authentication failed", res, AuthError)
    else
      raise_error("Authentication failed", res)
    end
  end
  js = checked_json(body, %w[apikey])
  apikey = js['apikey']
  return apikey
end

#bulk_import_delete_part(name, part_name, opts = {}) ⇒ Object

> nil



613
614
615
616
617
618
619
620
# File 'lib/td/client/api.rb', line 613

def bulk_import_delete_part(name, part_name, opts={})
  params = opts.dup
  code, body, res = post("/v3/bulk_import/delete_part/#{e name}/#{e part_name}", params)
  if code[0] != ?2
    raise_error("Delete a part failed", res)
  end
  return nil
end

#bulk_import_error_records(name, opts = {}, &block) ⇒ Object

> data…



664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# File 'lib/td/client/api.rb', line 664

def bulk_import_error_records(name, opts={}, &block)
  params = opts.dup
  code, body, res = get("/v3/bulk_import/error_records/#{e name}", params)
  if code != "200"
    raise_error("Failed to get bulk import error records", res)
  end
  if body.empty?
    if block
      return nil
    else
      return []
    end
  end
  require 'zlib'
  require 'stringio'
  require 'msgpack'
  require File.expand_path('compat_gzip_reader', File.dirname(__FILE__))
  u = MessagePack::Unpacker.new(Zlib::GzipReader.new(StringIO.new(body)))
  if block
    begin
      u.each(&block)
    rescue EOFError
    end
    nil
  else
    result = []
    begin
      u.each {|row|
        result << row
      }
    rescue EOFError
    end
    return result
  end
end

#bulk_import_upload_part(name, part_name, stream, size, opts = {}) ⇒ Object

> nil



604
605
606
607
608
609
610
# File 'lib/td/client/api.rb', line 604

def bulk_import_upload_part(name, part_name, stream, size, opts={})
  code, body, res = put("/v3/bulk_import/upload_part/#{e name}/#{e part_name}", stream, size)
  if code[0] != ?2
    raise_error("Upload a part failed", res)
  end
  return nil
end

#change_email(user, email) ⇒ Object

> true



1145
1146
1147
1148
1149
1150
1151
1152
# File 'lib/td/client/api.rb', line 1145

def change_email(user, email)
  params = {'email' => email}
  code, body, res = post("/v3/user/email/change/#{e user}", params)
  if code != "200"
    raise_error("Changing email failed", res)
  end
  return true
end

#change_my_password(old_password, password) ⇒ Object

> true



1194
1195
1196
1197
1198
1199
1200
1201
# File 'lib/td/client/api.rb', line 1194

def change_my_password(old_password, password)
  params = {'old_password' => old_password, 'password' => password}
  code, body, res = post("/v3/user/password/change", params)
  if code != "200"
    raise_error("Changing password failed", res)
  end
  return true
end

#change_password(user, password) ⇒ Object

> true



1184
1185
1186
1187
1188
1189
1190
1191
# File 'lib/td/client/api.rb', line 1184

def change_password(user, password)
  params = {'password' => password}
  code, body, res = post("/v3/user/password/change/#{e user}", params)
  if code != "200"
    raise_error("Changing password failed", res)
  end
  return true
end

#commit_bulk_import(name, opts = {}) ⇒ Object

> nil



654
655
656
657
658
659
660
661
# File 'lib/td/client/api.rb', line 654

def commit_bulk_import(name, opts={})
  params = opts.dup
  code, body, res = post("/v3/bulk_import/commit/#{e name}", params)
  if code != "200"
    raise_error("Commit bulk import failed", res)
  end
  return nil
end

#create_aggregation_attr_entry(name, entry_name, comment, db, table, method_name, parameters) ⇒ Object

> true



971
972
973
974
975
976
977
978
979
980
981
982
# File 'lib/td/client/api.rb', line 971

def create_aggregation_attr_entry(name, entry_name, comment, db, table, method_name, parameters)
  params = {}
  parameters.each_pair {|k,v|
    params["parameters[#{k}]"] = v.to_s
  }
  params['comment'] = comment if comment
  code, body, res = post("/v3/aggr/entry/attr/create/#{e name}/#{e entry_name}/#{e db}/#{e table}/#{e method_name}", params)
  if code != "200"
    raise_error("Create aggregation attr entry failed", res)
  end
  return true
end

#create_aggregation_log_entry(name, entry_name, comment, db, table, okeys, value_key, count_key) ⇒ Object

> true



946
947
948
949
950
951
952
953
954
955
956
957
958
959
# File 'lib/td/client/api.rb', line 946

def create_aggregation_log_entry(name, entry_name, comment, db, table, okeys, value_key, count_key)
  params = {}
  params['comment'] = comment if comment
  okeys.each_with_index {|okey,i|
    params["os[#{i}]"] = okey
  }
  params['value_key'] = value_key if value_key
  params['count_key'] = count_key if count_key
  code, body, res = post("/v3/aggr/entry/log/create/#{e name}/#{e entry_name}/#{e db}/#{e table}", params)
  if code != "200"
    raise_error("Create aggregation log entry failed", res)
  end
  return true
end

#create_aggregation_schema(name, relation_key, params = {}) ⇒ Object

> true



885
886
887
888
889
890
891
892
# File 'lib/td/client/api.rb', line 885

def create_aggregation_schema(name, relation_key, params={})
  params['relation_key'] = relation_key if relation_key
  code, body, res = post("/v3/aggr/create/#{e name}", params)
  if code != "200"
    raise_error("Create aggregation schema failed", res)
  end
  return true
end

#create_bulk_import(name, db, table, opts = {}) ⇒ Object

> nil



563
564
565
566
567
568
569
570
# File 'lib/td/client/api.rb', line 563

def create_bulk_import(name, db, table, opts={})
  params = opts.dup
  code, body, res = post("/v3/bulk_import/create/#{e name}/#{e db}/#{e table}", params)
  if code != "200"
    raise_error("Create bulk import failed", res)
  end
  return nil
end

#create_database(db, opts = {}) ⇒ Object

> true



235
236
237
238
239
240
241
242
# File 'lib/td/client/api.rb', line 235

def create_database(db, opts={})
  params = opts.dup
  code, body, res = post("/v3/database/create/#{e db}", params)
  if code != "200"
    raise_error("Create database failed", res)
  end
  return true
end

#create_item_table(db, table) ⇒ Object

> true



288
289
290
# File 'lib/td/client/api.rb', line 288

def create_item_table(db, table)
  create_table(db, table, :item)
end

#create_log_table(db, table) ⇒ Object

> true



283
284
285
# File 'lib/td/client/api.rb', line 283

def create_log_table(db, table)
  create_table(db, table, :log)
end

#create_organization(org) ⇒ Object

> true



1013
1014
1015
1016
1017
1018
1019
# File 'lib/td/client/api.rb', line 1013

def create_organization(org)
  code, body, res = post("/v3/organization/create/#{e org}")
  if code != "200"
    raise_error("Creating organization failed", res)
  end
  return true
end

#create_result(name, url, opts = {}) ⇒ Object

> true



845
846
847
848
849
850
851
852
# File 'lib/td/client/api.rb', line 845

def create_result(name, url, opts={})
  params = {'url'=>url}.merge(opts)
  code, body, res = post("/v3/result/create/#{e name}", params)
  if code != "200"
    raise_error("Create result table failed", res)
  end
  return true
end

#create_role(role, org) ⇒ Object

> true



1052
1053
1054
1055
1056
1057
1058
1059
# File 'lib/td/client/api.rb', line 1052

def create_role(role, org)
  params = {'organization'=>org}
  code, body, res = post("/v3/role/create/#{e role}", params)
  if code != "200"
    raise_error("Creating role failed", res)
  end
  return true
end

#create_schedule(name, opts) ⇒ Object

> start:String



705
706
707
708
709
710
711
712
713
# File 'lib/td/client/api.rb', line 705

def create_schedule(name, opts)
  params = opts.update({:type=> opts[:type] || opts['type'] || 'hive'})
  code, body, res = post("/v3/schedule/create/#{e name}", params)
  if code != "200"
    raise_error("Create schedule failed", res)
  end
  js = checked_json(body, %w[start])
  return js['start']
end

#delete_aggregation_attr_entry(name, entry_name) ⇒ Object

> true



985
986
987
988
989
990
991
# File 'lib/td/client/api.rb', line 985

def delete_aggregation_attr_entry(name, entry_name)
  code, body, res = post("/v3/aggr/entry/attr/delete/#{e name}/#{e entry_name}")
  if code != "200"
    raise_error("Delete aggregation attr entry failed", res)
  end
  return true
end

#delete_aggregation_log_entry(name, entry_name) ⇒ Object

> true



962
963
964
965
966
967
968
# File 'lib/td/client/api.rb', line 962

def delete_aggregation_log_entry(name, entry_name)
  code, body, res = post("/v3/aggr/entry/log/delete/#{e name}/#{e entry_name}")
  if code != "200"
    raise_error("Delete aggregation log entry failed", res)
  end
  return true
end

#delete_aggregation_schema(name) ⇒ Object

> true



895
896
897
898
899
900
901
# File 'lib/td/client/api.rb', line 895

def delete_aggregation_schema(name)
  code, body, res = post("/v3/aggr/delete/#{e name}")
  if code != "200"
    raise_error("Delete aggregation schema failed", res)
  end
  return true
end

#delete_bulk_import(name, opts = {}) ⇒ Object

> nil



573
574
575
576
577
578
579
580
# File 'lib/td/client/api.rb', line 573

def delete_bulk_import(name, opts={})
  params = opts.dup
  code, body, res = post("/v3/bulk_import/delete/#{e name}", params)
  if code != "200"
    raise_error("Delete bulk import failed", res)
  end
  return nil
end

#delete_database(db) ⇒ Object

> true



226
227
228
229
230
231
232
# File 'lib/td/client/api.rb', line 226

def delete_database(db)
  code, body, res = post("/v3/database/delete/#{e db}")
  if code != "200"
    raise_error("Delete database failed", res)
  end
  return true
end

#delete_ip_limit(organization) ⇒ Object



1289
1290
1291
1292
1293
1294
1295
1296
# File 'lib/td/client/api.rb', line 1289

def delete_ip_limit(organization)
  params = {'organization' => organization}
  code, body, res = post("/v3/ip_limit/delete", params)
  if code != "200"
    raise_error("Deleting IP range limitation failed", res)
  end
  return true
end

#delete_organization(org) ⇒ Object

> true



1022
1023
1024
1025
1026
1027
1028
# File 'lib/td/client/api.rb', line 1022

def delete_organization(org)
  code, body, res = post("/v3/organization/delete/#{e org}")
  if code != "200"
    raise_error("Deleting organization failed", res)
  end
  return true
end

#delete_result(name) ⇒ Object

> true



855
856
857
858
859
860
861
# File 'lib/td/client/api.rb', line 855

def delete_result(name)
  code, body, res = post("/v3/result/delete/#{e name}")
  if code != "200"
    raise_error("Delete result table failed", res)
  end
  return true
end

#delete_role(role) ⇒ Object

> true



1062
1063
1064
1065
1066
1067
1068
# File 'lib/td/client/api.rb', line 1062

def delete_role(role)
  code, body, res = post("/v3/role/delete/#{e role}")
  if code != "200"
    raise_error("Creating role failed", res)
  end
  return true
end

#delete_schedule(name) ⇒ Object

> cron:String, query:String



716
717
718
719
720
721
722
723
# File 'lib/td/client/api.rb', line 716

def delete_schedule(name)
  code, body, res = post("/v3/schedule/delete/#{e name}")
  if code != "200"
    raise_error("Delete schedule failed", res)
  end
  js = checked_json(body, %w[])
  return js['cron'], js["query"]
end

#delete_table(db, table) ⇒ Object

> type:Symbol



329
330
331
332
333
334
335
336
337
# File 'lib/td/client/api.rb', line 329

def delete_table(db, table)
  code, body, res = post("/v3/table/delete/#{e db}/#{e table}")
  if code != "200"
    raise_error("Delete table failed", res)
  end
  js = checked_json(body, %w[])
  type = (js['type'] || '?').to_sym
  return type
end

#export(db, table, storage_type, opts = {}) ⇒ Object

> jobId:String



530
531
532
533
534
535
536
537
538
539
# File 'lib/td/client/api.rb', line 530

def export(db, table, storage_type, opts={})
  params = opts.dup
  params['storage_type'] = storage_type
  code, body, res = post("/v3/export/run/#{e db}/#{e table}", params)
  if code != "200"
    raise_error("Export failed", res)
  end
  js = checked_json(body, %w[job_id])
  return js['job_id'].to_s
end

#freeze_bulk_import(name, opts = {}) ⇒ Object

> nil



623
624
625
626
627
628
629
630
# File 'lib/td/client/api.rb', line 623

def freeze_bulk_import(name, opts={})
  params = opts.dup
  code, body, res = post("/v3/bulk_import/freeze/#{e name}", params)
  if code != "200"
    raise_error("Freeze bulk import failed", res)
  end
  return nil
end

#grant_access_control(subject, action, scope, grant_option) ⇒ Object

Access Control API



1208
1209
1210
1211
1212
1213
1214
1215
# File 'lib/td/client/api.rb', line 1208

def grant_access_control(subject, action, scope, grant_option)
  params = {'subject'=>subject, 'action'=>action, 'scope'=>scope, 'grant_option'=>grant_option.to_s}
  code, body, res = post("/v3/acl/grant", params)
  if code != "200"
    raise_error("Granting access control failed", res)
  end
  return true
end

#grant_role(role, user) ⇒ Object

> true



1071
1072
1073
1074
1075
1076
1077
# File 'lib/td/client/api.rb', line 1071

def grant_role(role, user)
  code, body, res = post("/v3/role/grant/#{e role}/#{e user}")
  if code != "200"
    raise_error("Granting role failed", res)
  end
  return true
end

#history(name, from = 0, to = nil) ⇒ Object



758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
# File 'lib/td/client/api.rb', line 758

def history(name, from=0, to=nil)
  params = {}
  params['from'] = from.to_s if from
  params['to'] = to.to_s if to
  code, body, res = get("/v3/schedule/history/#{e name}", params)
  if code != "200"
    raise_error("List history failed", res)
  end
  js = checked_json(body, %w[history])
  result = []
  js['history'].each {|m|
    job_id = m['job_id']
    type = (m['type'] || '?').to_sym
    database = m['database']
    status = m['status']
    query = m['query']
    start_at = m['start_at']
    end_at = m['end_at']
    scheduled_at = m['scheduled_at']
    result_url = m['result']
    priority = m['priority']
    result << [scheduled_at, job_id, type, status, query, start_at, end_at, result_url, priority, database]
  }
  return result
end

#hive_query(q, db = nil, result_url = nil, priority = nil, retry_limit = nil, opts = {}) ⇒ Object

> jobId:String



502
503
504
# File 'lib/td/client/api.rb', line 502

def hive_query(q, db=nil, result_url=nil, priority=nil, retry_limit=nil, opts={})
  query(q, :hive, db, result_url, priority, retry_limit, opts)
end

#import(db, table, format, stream, size, unique_id = nil) ⇒ Object

> time:Float



807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
# File 'lib/td/client/api.rb', line 807

def import(db, table, format, stream, size, unique_id=nil)
  if unique_id
    path = "/v3/table/import_with_id/#{e db}/#{e table}/#{unique_id}/#{format}"
  else
    path = "/v3/table/import/#{e db}/#{e table}/#{format}"
  end
  opts = {}
  if @host == DEFAULT_ENDPOINT
    opts[:host] = DEFAULT_IMPORT_ENDPOINT
  end
  code, body, res = put(path, stream, size, opts)
  if code[0] != ?2
    raise_error("Import failed", res)
  end
  js = checked_json(body, %w[])
  time = js['time'].to_f
  return time
end

#job_result(job_id) ⇒ Object



436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/td/client/api.rb', line 436

def job_result(job_id)
  require 'msgpack'
  code, body, res = get("/v3/job/result/#{e job_id}", {'format'=>'msgpack'})
  if code != "200"
    raise_error("Get job result failed", res)
  end
  result = []
  MessagePack::Unpacker.new.feed_each(body) {|row|
    result << row
  }
  return result
end

#job_result_each(job_id, &block) ⇒ Object



469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/td/client/api.rb', line 469

def job_result_each(job_id, &block)
  require 'msgpack'
  get("/v3/job/result/#{e job_id}", {'format'=>'msgpack'}) {|res|
    if res.code != "200"
      raise_error("Get job result failed", res)
    end
    u = MessagePack::Unpacker.new
    res.each_fragment {|fragment|
      u.feed_each(fragment, &block)
    }
  }
  nil
end

#job_result_format(job_id, format, io = nil) ⇒ Object



449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
# File 'lib/td/client/api.rb', line 449

def job_result_format(job_id, format, io=nil)
  if io
    code, body, res = get("/v3/job/result/#{e job_id}", {'format'=>format}) {|res|
      if res.code != "200"
        raise_error("Get job result failed", res)
      end
      res.each_fragment {|fragment|
        io.write(fragment)
      }
    }
    nil
  else
    code, body, res = get("/v3/job/result/#{e job_id}", {'format'=>format})
    if res.code != "200"
      raise_error("Get job result failed", res)
    end
    body
  end
end

#job_result_raw(job_id, format) ⇒ Object



483
484
485
486
487
488
489
# File 'lib/td/client/api.rb', line 483

def job_result_raw(job_id, format)
  code, body, res = get("/v3/job/result/#{e job_id}", {'format'=>format})
  if code != "200"
    raise_error("Get job result failed", res)
  end
  return body
end

#job_status(job_id) ⇒ Object



426
427
428
429
430
431
432
433
434
# File 'lib/td/client/api.rb', line 426

def job_status(job_id)
  code, body, res = get("/v3/job/status/#{e job_id}")
  if code != "200"
    raise_error("Get job status failed", res)
  end

  js = checked_json(body, %w[status])
  return js['status']
end

#kill(job_id) ⇒ Object



491
492
493
494
495
496
497
498
499
# File 'lib/td/client/api.rb', line 491

def kill(job_id)
  code, body, res = post("/v3/job/kill/#{e job_id}")
  if code != "200"
    raise_error("Kill job failed", res)
  end
  js = checked_json(body, %w[])
  former_status = js['former_status']
  return former_status
end

#list_access_controlsObject

subject:String,action:String,scope:String


1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
# File 'lib/td/client/api.rb', line 1245

def list_access_controls
  code, body, res = get("/v3/acl/list")
  if code != "200"
    raise_error("Listing access control failed", res)
  end
  js = checked_json(body, %w[access_controls])
  acl = js["access_controls"].map {|roleinfo|
    subject = roleinfo['subject']
    action = roleinfo['action']
    scope = roleinfo['scope']
    grant_option = roleinfo['grant_option']
    [subject, action, scope, grant_option]
  }
  return acl
end

#list_aggregation_schemaObject

> [(name:String, relation_key:String)]



869
870
871
872
873
874
875
876
877
878
879
880
881
882
# File 'lib/td/client/api.rb', line 869

def list_aggregation_schema
  code, body, res = get("/v3/aggr/list")
  if code != "200"
    raise_error("List aggregation schema failed", res)
  end
  js = checked_json(body, %w[aggrs])
  result = js["aggrs"].map {|aggrinfo|
    name = aggrinfo['name'].to_s
    relation_key = aggrinfo['relation_key'].to_s
    timezone = aggrinfo['timezone'].to_s
    [name, relation_key, timezone]
  }
  return result
end

#list_apikeys(user) ⇒ Object

> [apikey:String]



1155
1156
1157
1158
1159
1160
1161
1162
# File 'lib/td/client/api.rb', line 1155

def list_apikeys(user)
  code, body, res = get("/v3/user/apikey/list/#{e user}")
  if code != "200"
    raise_error("List API keys failed", res)
  end
  js = checked_json(body, %w[apikeys])
  return js['apikeys']
end

#list_bulk_import_parts(name, opts = {}) ⇒ Object



593
594
595
596
597
598
599
600
601
# File 'lib/td/client/api.rb', line 593

def list_bulk_import_parts(name, opts={})
  params = opts.dup
  code, body, res = get("/v3/bulk_import/list_parts/#{e name}", params)
  if code != "200"
    raise_error("List bulk import parts failed", res)
  end
  js = checked_json(body, %w[parts])
  return js['parts']
end

#list_bulk_imports(opts = {}) ⇒ Object



583
584
585
586
587
588
589
590
591
# File 'lib/td/client/api.rb', line 583

def list_bulk_imports(opts={})
  params = opts.dup
  code, body, res = get("/v3/bulk_import/list", params)
  if code != "200"
    raise_error("List bulk imports failed", res)
  end
  js = checked_json(body, %w[bulk_imports])
  return js['bulk_imports']
end

#list_databasesObject

> [name:String]



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/td/client/api.rb', line 207

def list_databases
  code, body, res = get("/v3/database/list")
  if code != "200"
    raise_error("List databases failed", res)
  end
  js = checked_json(body, %w[databases])
  result = {}
  js["databases"].each {|m|
    name = m['name']
    count = m['count']
    created_at = m['created_at']
    updated_at = m['updated_at']
    organization = m['organization']
    result[name] = [count, created_at, updated_at, organization]
  }
  return result
end

#list_ip_limitsObject

IP Range Limit API



1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
# File 'lib/td/client/api.rb', line 1265

def list_ip_limits
  code, body, res = get("/v3/ip_limit/list")
  if code != "200"
    raise_error("Listing IP limitations failed", res)
  end
  js = checked_json(body, %w[ip_limits])
  lists = js["ip_limits"].map { |ip_limit|
    organization = ip_limit['organization']
    address = ip_limit['address']
    mask = ip_limit['mask']
    [organization, address, mask]
  }
  return lists
end

#list_jobs(from = 0, to = nil, status = nil, conditions = nil) ⇒ Object

> [(jobId:String, type:Symbol, status:String, start_at:String, end_at:String, result_url:String)]



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
# File 'lib/td/client/api.rb', line 367

def list_jobs(from=0, to=nil, status=nil, conditions=nil)
  params = {}
  params['from'] = from.to_s if from
  params['to'] = to.to_s if to
  params['status'] = status.to_s if status
  params.merge!(conditions) if conditions
  code, body, res = get("/v3/job/list", params)
  if code != "200"
    raise_error("List jobs failed", res)
  end
  js = checked_json(body, %w[jobs])
  result = []
  js['jobs'].each {|m|
    job_id = m['job_id']
    type = (m['type'] || '?').to_sym
    database = m['database']
    status = m['status']
    query = m['query']
    start_at = m['start_at']
    end_at = m['end_at']
    result_url = m['result']
    priority = m['priority']
    retry_limit = m['retry_limit']
    organization = m['organization']
    result << [job_id, type, status, query, start_at, end_at, result_url, priority, retry_limit, organization, database]
  }
  return result
end

#list_organizationsObject

> [name:String]



999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
# File 'lib/td/client/api.rb', line 999

def list_organizations
  code, body, res = get("/v3/organization/list")
  if code != "200"
    raise_error("List organizations failed", res)
  end
  js = checked_json(body, %w[organizations])
  result = js["organizations"].map {|orginfo|
    name = orginfo['name'].to_s
    name
  }
  return result
end

#list_resultObject

Result API



831
832
833
834
835
836
837
838
839
840
841
842
# File 'lib/td/client/api.rb', line 831

def list_result
  code, body, res = get("/v3/result/list")
  if code != "200"
    raise_error("List result table failed", res)
  end
  js = checked_json(body, %w[results])
  result = []
  js['results'].map {|m|
    result << [m['name'], m['url'], m['organization']]
  }
  return result
end

#list_rolesObject



1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
# File 'lib/td/client/api.rb', line 1036

def list_roles
  code, body, res = get("/v3/role/list")
  if code != "200"
    raise_error("List roles failed", res)
  end
  js = checked_json(body, %w[roles])
  result = js["roles"].map {|roleinfo|
    name = roleinfo['name']
    organization = roleinfo['organization']
    users = roleinfo['users']
    [name, organization, users]
  }
  return result
end

#list_schedulesObject

> [(name:String, cron:String, query:String, database:String, result_url:String)]



726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
# File 'lib/td/client/api.rb', line 726

def list_schedules
  code, body, res = get("/v3/schedule/list")
  if code != "200"
    raise_error("List schedules failed", res)
  end
  js = checked_json(body, %w[schedules])
  result = []
  js['schedules'].each {|m|
    name = m['name']
    cron = m['cron']
    query = m['query']
    database = m['database']
    result_url = m['result']
    timezone = m['timezone']
    delay = m['delay']
    next_time = m['next_time']
    priority = m['priority']
    retry_limit = m['retry_limit']
    organization = m['organization']
    result << [name, cron, query, database, result_url, timezone, delay, next_time, priority, retry_limit, organization]
  }
  return result
end

#list_tables(db) ⇒ Object

> => [type:Symbol, count:Integer]



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/td/client/api.rb', line 250

def list_tables(db)
  code, body, res = get("/v3/table/list/#{e db}")
  if code != "200"
    raise_error("List tables failed", res)
  end
  js = checked_json(body, %w[tables])
  result = {}
  js["tables"].map {|m|
    name = m['name']
    type = (m['type'] || '?').to_sym
    count = (m['count'] || 0).to_i  # TODO?
    created_at = m['created_at']
    updated_at = m['updated_at']
    last_import = m['counter_updated_at']
    last_log_timestamp = m['last_log_timestamp']
    estimated_storage_size = m['estimated_storage_size'].to_i
    schema = JSON.parse(m['schema'] || '[]')
    expire_days = m['expire_days']
    result[name] = [type, schema, count, created_at, updated_at, estimated_storage_size, last_import, last_log_timestamp, expire_days]
  }
  return result
end

#list_usersObject



1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
# File 'lib/td/client/api.rb', line 1109

def list_users
  code, body, res = get("/v3/user/list")
  if code != "200"
    raise_error("List users failed", res)
  end
  js = checked_json(body, %w[users])
  result = js["users"].map {|roleinfo|
    name = roleinfo['name']
    organization = roleinfo['organization']
    roles = roleinfo['roles']
    email = roleinfo['email']
    [name, organization, roles, email]
  }
  return result
end

#partial_delete(db, table, to, from, opts = {}) ⇒ Object

Partial delete API



546
547
548
549
550
551
552
553
554
555
556
# File 'lib/td/client/api.rb', line 546

def partial_delete(db, table, to, from, opts={})
  params = opts.dup
  params['to'] = to.to_s
  params['from'] = from.to_s
  code, body, res = post("/v3/table/partialdelete/#{e db}/#{e table}", params)
  if code != "200"
    raise_error("Partial delete failed", res)
  end
  js = checked_json(body, %w[job_id])
  return js['job_id'].to_s
end

#perform_bulk_import(name, opts = {}) ⇒ Object

> jobId:String



643
644
645
646
647
648
649
650
651
# File 'lib/td/client/api.rb', line 643

def perform_bulk_import(name, opts={})
  params = opts.dup
  code, body, res = post("/v3/bulk_import/perform/#{e name}", params)
  if code != "200"
    raise_error("Perform bulk import failed", res)
  end
  js = checked_json(body, %w[job_id])
  return js['job_id'].to_s
end

#pig_query(q, db = nil, result_url = nil, priority = nil, retry_limit = nil, opts = {}) ⇒ Object

> jobId:String



507
508
509
# File 'lib/td/client/api.rb', line 507

def pig_query(q, db=nil, result_url=nil, priority=nil, retry_limit=nil, opts={})
  query(q, :pig, db, result_url, priority, retry_limit, opts)
end

#query(q, type = :hive, db = nil, result_url = nil, priority = nil, retry_limit = nil, opts = {}) ⇒ Object

> jobId:String



512
513
514
515
516
517
518
519
520
521
522
523
# File 'lib/td/client/api.rb', line 512

def query(q, type=:hive, db=nil, result_url=nil, priority=nil, retry_limit=nil, opts={})
  params = {'query' => q}.merge(opts)
  params['result'] = result_url if result_url
  params['priority'] = priority if priority
  params['retry_limit'] = retry_limit if retry_limit
  code, body, res = post("/v3/job/issue/#{type}/#{e db}", params)
  if code != "200"
    raise_error("Query failed", res)
  end
  js = checked_json(body, %w[job_id])
  return js['job_id'].to_s
end

#remove_apikey(user, apikey) ⇒ Object

> true



1174
1175
1176
1177
1178
1179
1180
1181
# File 'lib/td/client/api.rb', line 1174

def remove_apikey(user, apikey)
  params = {'apikey' => apikey}
  code, body, res = post("/v3/user/apikey/remove/#{e user}", params)
  if code != "200"
    raise_error("Removing API key failed", res)
  end
  return true
end

#remove_user(user) ⇒ Object

> true



1136
1137
1138
1139
1140
1141
1142
# File 'lib/td/client/api.rb', line 1136

def remove_user(user)
  code, body, res = post("/v3/user/remove/#{e user}")
  if code != "200"
    raise_error("Removing user failed", res)
  end
  return true
end

#revoke_access_control(subject, action, scope) ⇒ Object



1217
1218
1219
1220
1221
1222
1223
1224
# File 'lib/td/client/api.rb', line 1217

def revoke_access_control(subject, action, scope)
  params = {'subject'=>subject, 'action'=>action, 'scope'=>scope}
  code, body, res = post("/v3/acl/revoke", params)
  if code != "200"
    raise_error("Revoking access control failed", res)
  end
  return true
end

#revoke_role(role, user) ⇒ Object

> true



1080
1081
1082
1083
1084
1085
1086
# File 'lib/td/client/api.rb', line 1080

def revoke_role(role, user)
  code, body, res = post("/v3/role/revoke/#{e role}/#{e user}")
  if code != "200"
    raise_error("Revoking role failed", res)
  end
  return true
end

#run_schedule(name, time, num) ⇒ Object



784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
# File 'lib/td/client/api.rb', line 784

def run_schedule(name, time, num)
  params = {}
  params = {'num' => num} if num
  code, body, res = post("/v3/schedule/run/#{e name}/#{e time}", params)
  if code != "200"
    raise_error("Run schedule failed", res)
  end
  js = checked_json(body, %w[jobs])
  result = []
  js['jobs'].each {|m|
    job_id = m['job_id']
    scheduled_at = m['scheduled_at']
    type = (m['type'] || '?').to_sym
    result << [job_id, type, scheduled_at]
  }
  return result
end

#server_statusObject

> status:String



1303
1304
1305
1306
1307
1308
1309
1310
1311
# File 'lib/td/client/api.rb', line 1303

def server_status
  code, body, res = get('/v3/system/server_status')
  if code != "200"
    return "Server is down (#{code})"
  end
  js = checked_json(body, %w[status])
  status = js['status']
  return status
end

#set_ip_limit(organization, ip_ranges) ⇒ Object



1280
1281
1282
1283
1284
1285
1286
1287
# File 'lib/td/client/api.rb', line 1280

def set_ip_limit(organization, ip_ranges)
  params = {'organization' => organization, 'ip_ranges' => ip_ranges}
  code, body, res = post("/v3/ip_limit/set", params)
  if code != "200"
    raise_error("Setting IP limitation failed", res)
  end
  return true
end

#show_accountObject

Account API



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/td/client/api.rb', line 169

def 
  code, body, res = get("/v3/account/show")
  if code != "200"
    raise_error("Show account failed", res)
  end
  js = checked_json(body, %w[account])
  a = js["account"]
   = a['id'].to_i
  plan = a['plan'].to_i
  storage_size = a['storage_size'].to_i
  guaranteed_cores = a['guaranteed_cores'].to_i
  maximum_cores = a['maximum_cores'].to_i
  created_at = a['created_at']
  return [, plan, storage_size, guaranteed_cores, maximum_cores, created_at]
end

#show_aggregation_schema(name) ⇒ Object

> [

{
  relation_key: String,
  logs: (entry_name:String, comment:String, database:String, table:String,
         os:Array[String], value_key:String?, count_key:String?),
  attrs: (entry_name:String, comment:String, database:String, table:String,
         method_name:String, parameters:Hash[String=>Object])
}

]



912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
# File 'lib/td/client/api.rb', line 912

def show_aggregation_schema(name)
  code, body, res = get("/v3/aggr/show/#{e name}")
  if code != "200"
    raise_error("Show aggregation schema failed", res)
  end
  js = checked_json(body, %w[relation_key logs attrs])
  relation_key = js['relation_key']
  logs = js['logs'].map {|loginfo|
    entry_name = loginfo['name'].to_s
    comment = loginfo['comment'].to_s
    database = loginfo['database'].to_s
    table = loginfo['table'].to_s
    os = loginfo['os']
    value_key = loginfo['value_key'].to_s
    count_key = loginfo['count_key'].to_s
    value_key = nil if value_key.empty?
    count_key = nil if count_key.empty?
    [entry_name, comment, database, table, os, value_key, count_key]
  }
  attrs = js['attrs'].map {|attrinfo|
    entry_name = attrinfo['name'].to_s
    comment = attrinfo['comment'].to_s
    database = attrinfo['database'].to_s
    table = attrinfo['table'].to_s
    method_name = attrinfo['method_name'].to_s
    parameters = attrinfo['parameters'].to_s
    parameters = "{}" if parameters.empty?
    parameters = JSON.parse(parameters)
    [entry_name, comment, database, table, method_name, parameters]
  }
  return [relation_key, logs, attrs]
end

#show_job(job_id) ⇒ Object

> (type:Symbol, status:String, result:String, url:String, result:String)



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/td/client/api.rb', line 397

def show_job(job_id)
  # use v3/job/status instead of v3/job/show to poll finish of a job
  code, body, res = get("/v3/job/show/#{e job_id}")
  if code != "200"
    raise_error("Show job failed", res)
  end
  js = checked_json(body, %w[status])
  # TODO debug
  type = (js['type'] || '?').to_sym  # TODO
  database = js['database']
  query = js['query']
  status = js['status']
  debug = js['debug']
  url = js['url']
  start_at = js['start_at']
  end_at = js['end_at']
  result = js['result']
  hive_result_schema = (js['hive_result_schema'] || '')
  if hive_result_schema.empty?
    hive_result_schema = nil
  else
    hive_result_schema = JSON.parse(hive_result_schema)
  end
  priority = js['priority']
  retry_limit = js['retry_limit']
  organization = js['organization']
  return [type, query, status, url, debug, start_at, end_at, result, hive_result_schema, priority, retry_limit, organization, database]
end

#swap_table(db, table1, table2) ⇒ Object

> true



303
304
305
306
307
308
309
# File 'lib/td/client/api.rb', line 303

def swap_table(db, table1, table2)
  code, body, res = post("/v3/table/swap/#{e db}/#{e table1}/#{e table2}")
  if code != "200"
    raise_error("Swap tables failed", res)
  end
  return true
end

#tail(db, table, count, to, from, &block) ⇒ Object



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/td/client/api.rb', line 339

def tail(db, table, count, to, from, &block)
  params = {'format' => 'msgpack'}
  params['count'] = count.to_s if count
  params['to'] = to.to_s if to
  params['from'] = from.to_s if from
  code, body, res = get("/v3/table/tail/#{e db}/#{e table}", params)
  if code != "200"
    raise_error("Tail table failed", res)
  end
  require 'msgpack'
  if block
    MessagePack::Unpacker.new.feed_each(body, &block)
    nil
  else
    result = []
    MessagePack::Unpacker.new.feed_each(body) {|row|
      result << row
    }
    return result
  end
end

#test_access_control(user, action, scope) ⇒ Object

true, [subject:String,action:String,scope:String]


1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
# File 'lib/td/client/api.rb', line 1227

def test_access_control(user, action, scope)
  params = {'user'=>user, 'action'=>action, 'scope'=>scope}
  code, body, res = get("/v3/acl/test", params)
  if code != "200"
    raise_error("Testing access control failed", res)
  end
  js = checked_json(body, %w[permission access_controls])
  perm = js["permission"]
  acl = js["access_controls"].map {|roleinfo|
    subject = roleinfo['subject']
    action = roleinfo['action']
    scope = roleinfo['scope']
    [name, action, scope]
  }
  return perm, acl
end

#unfreeze_bulk_import(name, opts = {}) ⇒ Object

> nil



633
634
635
636
637
638
639
640
# File 'lib/td/client/api.rb', line 633

def unfreeze_bulk_import(name, opts={})
  params = opts.dup
  code, body, res = post("/v3/bulk_import/unfreeze/#{e name}", params)
  if code != "200"
    raise_error("Unfreeze bulk import failed", res)
  end
  return nil
end

#update_expire(db, table, expire_days) ⇒ Object



320
321
322
323
324
325
326
# File 'lib/td/client/api.rb', line 320

def update_expire(db, table, expire_days)
  code, body, res = post("/v3/table/update/#{e db}/#{e table}", {'expire_days'=>expire_days})
  if code != "200"
    raise_error("Update table expiration failed", res)
  end
  return true
end

#update_schedule(name, params) ⇒ Object



750
751
752
753
754
755
756
# File 'lib/td/client/api.rb', line 750

def update_schedule(name, params)
  code, body, res = get("/v3/schedule/update/#{e name}", params)
  if code != "200"
    raise_error("Update schedule failed", res)
  end
  return nil
end

#update_schema(db, table, schema_json) ⇒ Object

> true



312
313
314
315
316
317
318
# File 'lib/td/client/api.rb', line 312

def update_schema(db, table, schema_json)
  code, body, res = post("/v3/table/update-schema/#{e db}/#{e table}", {'schema'=>schema_json})
  if code != "200"
    raise_error("Create schema table failed", res)
  end
  return true
end