Class: Zillabyte::API

Inherits:
Object
  • Object
show all
Defined in:
lib/zillabyte/api/settings.rb,
lib/zillabyte/api.rb

Defined Under Namespace

Classes: Apps, Base, Components, Data, Flows, Keys, Logs, Metrics, Queries, SemanticTags, Sources, Zillalogs

Constant Summary collapse

CASPERJS_BIN =

PY_VIRTUAL_ENV_DIR = "/tmp/vEnv"

"/usr/local/bin/casperjs"
API_CLIENT_JS =
File.join(ENV['HOME'], "zb1/api.client.js/api.coffee")
NODEJS_BIN =
"/usr/local/bin/node"
HEADERS =
{
  'Accept'                => 'application/json',
  'Content-Type'          => 'application/json',
  # 'Accept-Encoding'       => 'gzip',
  'User-Agent'            => "zillabyte/#{Zillabyte::CLI::VERSION}",
  'X-Ruby-Version'        => RUBY_VERSION,
  'X-Ruby-Platform'       => RUBY_PLATFORM
}
OPTIONS =
{
  :headers  => {},
  :host     => ENV['ZILLABYTE_API_HOST'] || 'api.zillabyte.com',
  :port     => (ENV['ZILLABYTE_API_PORT'] || '80').to_i,
  :nonblock => false,
  :scheme   => 'http'
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ API

Returns a new instance of API.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/zillabyte/api.rb', line 40

def initialize(options={})
  options = OPTIONS.merge(options)
  @session = options.delete(:session)
  @api_key = options.delete(:api_key) || ENV['ZILLABYTE_API_KEY']
  
  options[:headers] = HEADERS.merge({ 
    'Authorization' => "auth_token #{@api_key}",
  }).merge(options[:headers])

  @options = options.clone
  @options[:bubble_exceptions] = ENV['BUBBLE_EXCEPTIONS'] || false
  @connection = Excon.new("#{options[:scheme]}://#{options[:host]}", options)

end

Class Method Details

.load ⇒ Object



237
238
239
240
241
242
243
244
245
246
# File 'lib/zillabyte/api.rb', line 237

def self.load
  require File.join(File.dirname(__FILE__), "api", "base.rb")
  Dir[File.join(File.dirname(__FILE__), "api", "*.rb")].sort.each do |file|
    require file
  end
  
  Dir[File.join(File.dirname(__FILE__), "api", "helpers", "*.rb")].sort.each do |file|
    require file
  end
end

Instance Method Details

#apps ⇒ Object Also known as: app



197
198
199
# File 'lib/zillabyte/api.rb', line 197

def apps
  @_apps ||= ::Zillabyte::API::Apps.new(self)
end

#collectors ⇒ Object Also known as: collector



227
228
229
# File 'lib/zillabyte/api.rb', line 227

def collectors
  @_collectors ||= ::Zillabyte::API::Collectors.new(self)
end

#components ⇒ Object Also known as: component



207
208
209
# File 'lib/zillabyte/api.rb', line 207

def components
  @_components ||= ::Zillabyte::API::Components.new(self)
end

#connection ⇒ Object



56
57
58
# File 'lib/zillabyte/api.rb', line 56

def connection
  @connection
end

#data ⇒ Object



180
181
182
# File 'lib/zillabyte/api.rb', line 180

def data
  @_data ||= ::Zillabyte::API::Data.new(self)
end

#flows ⇒ Object Also known as: flow



202
203
204
# File 'lib/zillabyte/api.rb', line 202

def flows
  @_flows || ::Zillabyte::API::Flows.new(self)
end

#headers ⇒ Object



61
62
63
# File 'lib/zillabyte/api.rb', line 61

def headers
  @options[:headers]
end

#host ⇒ Object



66
67
68
# File 'lib/zillabyte/api.rb', line 66

def host
  @options[:host]
end

#keys ⇒ Object



188
189
190
# File 'lib/zillabyte/api.rb', line 188

def keys
  @_keys ||= ::Zillabyte::API::Keys.new(self)
end

#logs ⇒ Object



184
185
186
# File 'lib/zillabyte/api.rb', line 184

def logs
  @_logs ||= ::Zillabyte::API::Logs.new(self)
end

#metrics ⇒ Object Also known as: metric



212
213
214
# File 'lib/zillabyte/api.rb', line 212

def metrics
  @_metrics ||= ::Zillabyte::API::Metrics.new(self)
end

#queries ⇒ Object Also known as: query



192
193
194
# File 'lib/zillabyte/api.rb', line 192

def queries
  @_queries ||= ::Zillabyte::API::Queries.new(self)
end

#request(params, &block) ⇒ Object



71
72
73
74
75
76
77
78
79
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/zillabyte/api.rb', line 71

def request(params, &block)

  if @session.nil?
    error "no session associated with request"
  end

  type = nil
  begin

    # If a block is given, then we assume we're streaming (i.e. for logs)
    if block_given?
      
      # We tell excon to emit a chunk ever 50 bytes.  This is an excon thing, doesn't 
      # affect the network IO chunk size
      params[:chunk_size] = 50;
      last_string = ""
      
      # Executed on each chunk excon bubbles up
      params[:response_block] = lambda do |chunk, remaining_bytes, total_bytes|

        # Debug helper
        puts chunk if ENV["ZB_DEBUG"]

        # assume single-line json, split by '\n'
        last_string += chunk
        ary = last_string.split("\n", -1)
        
        # Are we at the end of a JSON record? 
        if ary.size > 1
          last_string = ary.last + (if last_string.end_with?("\n") then "\n" else "" end)
          json_records = ary[0..-2]
          json_records.each do |json_record|
            
            # Blank?
            next if json_record.strip == ""
            
            if json_record.start_with?("HTTP/1.1 50")
              @session.error("internal server error (code 500)", type)
            end
            
            # Offer all the json records to the listening block
            begin
              block.call(JSON.parse(json_record))
            rescue JSON::ParserError => e
              @session.error("unable to parse logs", type)
            end
            
          end
        end
      end
    end

    # Execute the request
    response = @connection.request(params)




  rescue Excon::Errors::HTTPStatusError => error

      
    # Show helpful error message
    if error.response.body
      begin
        hash = JSON.parse(error.response.body)
        if hash['error_message']
          @session.error(hash['error_message'], type)

        end
      rescue JSON::ParserError => e
        # Trickle to generic message below
      end
    end


    @session.error("internal server error:: #{error}", type)
      
    raise error
  end
 
  if response.body && !response.body.empty?
    # decompress_response!(response)
    begin
      response.body = JSON.parse(response.body)
    rescue Exception => e
      raise e if @options[:bubble_exceptions]
      @session.error("unknown server response: \n #{response.body}", type)
    end
  end
  
  # Errors?
  if response.body.is_a?(Hash)
    if response.body["status"] == "error"
      if response.body["error"] == "authentication_error"
        @session.error("authentication error. run 'zillabyte login'", type)
      else
        @session.error(response.body["error_message"],type)
      end
    end
  end
  

  # reset (non-persistent) connection
  @connection.reset

  response
end

#semantic_tags ⇒ Object



232
233
234
# File 'lib/zillabyte/api.rb', line 232

def semantic_tags
  @_rules ||= ::Zillabyte::API::SemanticTags.new(self)
end

#sources ⇒ Object Also known as: source



222
223
224
# File 'lib/zillabyte/api.rb', line 222

def sources
  @_sources ||= ::Zillabyte::API::Sources.new(self)
end

#zillalogs ⇒ Object Also known as: zillalog



217
218
219
# File 'lib/zillabyte/api.rb', line 217

def zillalogs
  @_rules ||= ::Zillabyte::API::Zillalogs.new(self)
end