Class: Zillabyte::API

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

Defined Under Namespace

Classes: Apps, Base, Components, Data, Flows, Keys, Logs, Metrics, 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'
}

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ API

Returns a new instance of API.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/zillabyte/api.rb', line 24

def initialize(options={})
  require("excon")
  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

Instance Method Details

#appsObject Also known as: app



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

def apps
  require("zillabyte/api/apps")
  @_apps ||= ::Zillabyte::API::Apps.new(self)
end

#collectorsObject Also known as: collector



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

def collectors
  require("zillabyte/api/collectors")
  @_collectors ||= ::Zillabyte::API::Collectors.new(self)
end

#componentsObject Also known as: component



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

def components
  require("zillabyte/api/components")
  @_components ||= ::Zillabyte::API::Components.new(self)
end

#connectionObject



41
42
43
# File 'lib/zillabyte/api.rb', line 41

def connection
  @connection
end

#dataObject



164
165
166
167
# File 'lib/zillabyte/api.rb', line 164

def data
  require("zillabyte/api/data")
  @_data ||= ::Zillabyte::API::Data.new(self)
end

#flowsObject Also known as: flow



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

def flows
  require("zillabyte/api/flows")
  @_flows || ::Zillabyte::API::Flows.new(self)
end

#headersObject



46
47
48
# File 'lib/zillabyte/api.rb', line 46

def headers
  @options[:headers]
end

#hostObject



51
52
53
# File 'lib/zillabyte/api.rb', line 51

def host
  @options[:host]
end

#keysObject



174
175
176
177
# File 'lib/zillabyte/api.rb', line 174

def keys
  require("zillabyte/api/keys")
  @_keys ||= ::Zillabyte::API::Keys.new(self)
end

#logsObject



169
170
171
172
# File 'lib/zillabyte/api.rb', line 169

def logs
  require("zillabyte/api/logs")
  @_logs ||= ::Zillabyte::API::Logs.new(self)
end

#metricsObject Also known as: metric



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

def metrics
  require("zillabyte/api/metrics")
  @_metrics ||= ::Zillabyte::API::Metrics.new(self)
end

#queriesObject Also known as: query



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

def queries
  require("zillabyte/api/queries")
  @_queries ||= ::Zillabyte::API::Queries.new(self)
end

#request(params, &block) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
# File 'lib/zillabyte/api.rb', line 56

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'].to_s, 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_tagsObject



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

def semantic_tags
  require("zillabyte/api/semantic_tags")
  @_rules ||= ::Zillabyte::API::SemanticTags.new(self)
end

#sourcesObject Also known as: source



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

def sources
  require("zillabyte/api/sources")
  @_sources ||= ::Zillabyte::API::Sources.new(self)
end

#zillalogsObject Also known as: zillalog



209
210
211
212
# File 'lib/zillabyte/api.rb', line 209

def zillalogs
  require("zilabyte/api/zillalogs")
  @_rules ||= ::Zillabyte::API::Zillalogs.new(self)
end