Class: Fluent::BigQueryOutput

Inherits:
BufferedOutput
  • Object
show all
Defined in:
lib/fluent/plugin/out_bigquery.rb

Overview

TODO: error classes for each api error responses class BigQueryAPIError < StandardError end

Instance Method Summary collapse

Constructor Details

#initialize ⇒ BigQueryOutput

Table types https://developers.google.com/bigquery/docs/tables

type - The following data types are supported; see Data Formats for details on each data type: STRING INTEGER FLOAT BOOLEAN RECORD A JSON object, used when importing nested records. This type is only available when using JSON source files.

mode - Whether a field can be null. The following values are supported: NULLABLE - The cell can be null. REQUIRED - The cell cannot be null. REPEATED - Zero or more repeated simple or nested subfields. This mode is only supported when using JSON source files.



113
114
115
116
117
118
# File 'lib/fluent/plugin/out_bigquery.rb', line 113

def initialize
  super
  require 'google/api_client'
  require 'google/api_client/client_secrets'
  require 'google/api_client/auth/installed_app'
end

Instance Method Details

#client ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/fluent/plugin/out_bigquery.rb', line 175

def client
  return @cached_client if @cached_client && @cached_client_expiration > Time.now

  client = Google::APIClient.new(
    :application_name => 'Fluentd BigQuery plugin',
    :application_version => Fluent::BigQueryPlugin::VERSION
  )

  key = Google::APIClient::PKCS12.load_key( @private_key_path, @private_key_passphrase )
  asserter = Google::APIClient::JWTAsserter.new(
    @email,
    "https://www.googleapis.com/auth/bigquery",
    key
  )
  # refresh_auth
  client.authorization = asserter.authorize
  @cached_client_expiration = Time.now + 1800
  @cached_client = client
end

#configure(conf) ⇒ Object



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
# File 'lib/fluent/plugin/out_bigquery.rb', line 120

def configure(conf)
  super

  if (!@table && !@tables) || (@table && @table)
    raise Fluent::ConfigError, "'table' or 'tables' must be specified, and both are invalid"
  end

  @tablelist = @tables ? @tables.split(',') : [@table]

  @fields = {}
  if @field_string
    @field_string.split(',').each do |fieldname|
      @fields[fieldname] = :string
    end
  end
  if @field_integer
    @field_integer.split(',').each do |fieldname|
      @fields[fieldname] = :integer
    end
  end
  if @field_float
    @field_float.split(',').each do |fieldname|
      @fields[fieldname] = :float
    end
  end
  if @field_boolean
    @field_boolean.split(',').each do |fieldname|
      @fields[fieldname] = :boolean
    end
  end

  if @localtime.nil?
    if @utc
      @localtime = false
    end
  end
  @timef = TimeFormatter.new(@time_format, @localtime)
end

#format_record(record) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/fluent/plugin/out_bigquery.rb', line 230

def format_record(record)
  out = {}
  @fields.each do |key, type|
    value = record[key]
    next if value.nil? # field does not exists, or null value
    out[key] = case type
               when :string  then record[key].to_s
               when :integer then record[key].to_i
               when :float   then record[key].to_f
               when :boolean then !!record[key]
               # when :record
               else
                 raise "BUG: unknown field type #{type}"
               end
  end
  out
end

#format_stream(tag, es) ⇒ Object



248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/fluent/plugin/out_bigquery.rb', line 248

def format_stream(tag, es)
  super
  buf = ''
  es.each do |time, record|
    row = if @time_field
            format_record(record.merge({@time_field => @timef.format(time)}))
          else
            format_record(record)
          end
    buf << {"json" => row}.to_msgpack unless row.empty?
  end
  buf
end

#insert(table_id, rows) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/fluent/plugin/out_bigquery.rb', line 195

def insert(table_id, rows)
  res = client().execute(
    :api_method => @bq.tabledata.insert_all,
    :parameters => {
      'projectId' => @project,
      'datasetId' => @dataset,
      'tableId' => table_id,
    },
    :body_object => {
      "rows" => rows
    }
  )
  if res.status != 200
    # api_error? -> client cache clear
    @cached_client = nil

    message = res.body
    if res.body =~ /^\{/
      begin
        res_obj = JSON.parse(res.body)
        message = res_obj['error']['message'] || res.body
      rescue => e
        $log.warn "Parse error: google api error response body", :body => res.body
      end
    end
    $log.error "tabledata.insertAll API", :project_id => @project_id, :dataset => @dataset_id, :table => table_id, :code => res.status, :message => message
    raise "failed to insert into bigquery" # TODO: error class
  end
end

#load ⇒ Object

Raises:

  • (NotImplementedError)


225
226
227
228
# File 'lib/fluent/plugin/out_bigquery.rb', line 225

def load
  # https://developers.google.com/bigquery/loading-data-into-bigquery#loaddatapostrequest
  raise NotImplementedError # TODO
end

#shutdown ⇒ Object



170
171
172
173
# File 'lib/fluent/plugin/out_bigquery.rb', line 170

def shutdown
  super
  # nothing to do
end

#start ⇒ Object



159
160
161
162
163
164
165
166
167
168
# File 'lib/fluent/plugin/out_bigquery.rb', line 159

def start
  super

  @bq = client.discovered_api("bigquery", "v2") # TODO: refresh with specified expiration
  @cached_client = nil
  @cached_client_expiration = nil

  @tables_queue = @tablelist.dup.shuffle
  @tables_mutex = Mutex.new
end

#write(chunk) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/fluent/plugin/out_bigquery.rb', line 262

def write(chunk)
  rows = []
  chunk.msgpack_each do |row_object|
    # TODO: row size limit
    rows << row_object
  end

  # TODO: method

  insert_table = @tables_mutex.synchronize do
    t = @tables_queue.shift
    @tables_queue.push t
    t
  end
  insert(insert_table, rows)
end