forked from fluent/fluentd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.rb
421 lines (360 loc) · 12.6 KB
/
time.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
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
411
412
413
414
415
416
417
418
419
420
421
#
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'time'
require 'msgpack'
require 'strptime'
require 'fluent/timezone'
require 'fluent/configurable'
require 'fluent/config/error'
module Fluent
class EventTime
TYPE = 0
FORMATTER = Strftime.new('%Y-%m-%d %H:%M:%S.%N %z')
def initialize(sec, nsec = 0)
@sec = sec
@nsec = nsec
end
def ==(other)
if other.is_a?(Fluent::EventTime)
@sec == other.sec
else
@sec == other
end
end
def sec
@sec
end
def nsec
@nsec
end
def to_int
@sec
end
def to_f
@sec + @nsec / 1_000_000_000.0
end
# for Time.at
def to_r
Rational(@sec * 1_000_000_000 + @nsec, 1_000_000_000)
end
# for > and others
def coerce(other)
[other, @sec]
end
def to_s
@sec.to_s
end
def to_json(*args)
@sec.to_s
end
def to_msgpack(io = nil)
@sec.to_msgpack(io)
end
def to_msgpack_ext
[@sec, @nsec].pack('NN')
end
def self.from_msgpack_ext(data)
new(*data.unpack('NN'))
end
def self.from_time(time)
Fluent::EventTime.new(time.to_i, time.nsec)
end
def self.eq?(a, b)
if a.is_a?(Fluent::EventTime) && b.is_a?(Fluent::EventTime)
a.sec == b.sec && a.nsec == b.nsec
else
a == b
end
end
def self.now
from_time(Time.now)
end
def self.parse(*args)
from_time(Time.parse(*args))
end
## TODO: For performance, implement +, -, and so on
def method_missing(name, *args, &block)
@sec.send(name, *args, &block)
end
def inspect
FORMATTER.exec(Time.at(self))
end
end
module TimeMixin
TIME_TYPES = ['string', 'unixtime', 'float']
TIME_PARAMETERS = [
[:time_format, :string, {default: nil}],
[:localtime, :bool, {default: true}], # UTC if :localtime is false and :timezone is nil
[:utc, :bool, {default: false}], # to turn :localtime false
[:timezone, :string, {default: nil}],
]
TIME_FULL_PARAMETERS = [
# To avoid to define :time_type twice (in plugin_helper/inject)
[:time_type, :enum, {default: :string, list: TIME_TYPES.map(&:to_sym)}],
] + TIME_PARAMETERS
module TimeParameters
include Fluent::Configurable
TIME_FULL_PARAMETERS.each do |name, type, opts|
config_param name, type, opts
end
def configure(conf)
if conf.has_key?('localtime') || conf.has_key?('utc')
if conf.has_key?('localtime') && conf.has_key?('utc')
raise Fluent::ConfigError, "both of utc and localtime are specified, use only one of them"
elsif conf.has_key?('localtime')
conf['localtime'] = Fluent::Config.bool_value(conf['localtime'])
elsif conf.has_key?('utc')
conf['localtime'] = !(Fluent::Config.bool_value(conf['utc']))
# Specifying "localtime false" means using UTC in TimeFormatter
# And specifying "utc" is different from specifying "timezone +0000"(it's not always UTC).
# There are difference between "Z" and "+0000" in timezone formatting.
# TODO: add kwargs to TimeFormatter to specify "using localtime", "using UTC" or "using specified timezone" in more explicit way
end
end
super
Fluent::Timezone.validate!(@timezone) if @timezone
end
end
module Parser
def self.included(mod)
mod.include TimeParameters
end
def time_parser_create(type: @time_type, format: @time_format, timezone: @timezone, force_localtime: false)
return NumericTimeParser.new(type) if type != :string
return TimeParser.new(format, true, nil) if force_localtime
localtime = @localtime && (timezone.nil? && !@utc)
TimeParser.new(format, localtime, timezone)
end
end
module Formatter
def self.included(mod)
mod.include TimeParameters
end
def time_formatter_create(type: @time_type, format: @time_format, timezone: @timezone, force_localtime: false)
return NumericTimeFormatter.new(type) if type != :string
return TimeFormatter.new(format, true, nil) if force_localtime
localtime = @localtime && (timezone.nil? && !@utc)
TimeFormatter.new(format, localtime, timezone)
end
end
end
class TimeParser
class TimeParseError < StandardError; end
def initialize(format = nil, localtime = true, timezone = nil)
if format.nil? && (timezone || !localtime)
raise Fluent::ConfigError, "specifying timezone requires time format"
end
@cache1_key = nil
@cache1_time = nil
@cache2_key = nil
@cache2_time = nil
format_with_timezone = format && (format.include?("%z") || format.include?("%Z"))
# unixtime_in_expected_tz = unixtime_in_localtime + offset_diff
offset_diff = case
when format_with_timezone then nil
when timezone then Time.now.localtime.utc_offset - Time.zone_offset(timezone)
when localtime then 0
else Time.now.localtime.utc_offset # utc
end
strptime = format && (Strptime.new(format) rescue nil)
@parse = case
when format_with_timezone && strptime then ->(v){ Fluent::EventTime.from_time(strptime.exec(v)) }
when format_with_timezone then ->(v){ Fluent::EventTime.from_time(Time.strptime(v, format)) }
when format == '%iso8601' then ->(v){ Fluent::EventTime.from_time(Time.iso8601(v)) }
when strptime then ->(v){ t = strptime.exec(v); Fluent::EventTime.new(t.to_i + offset_diff, t.nsec) }
when format then ->(v){ t = Time.strptime(v, format); Fluent::EventTime.new(t.to_i + offset_diff, t.nsec) }
else ->(v){ Fluent::EventTime.parse(v) }
end
end
# TODO: new cache mechanism using format string
def parse(value)
unless value.is_a?(String)
raise TimeParseError, "value must be string: #{value}"
end
if @cache1_key == value
return @cache1_time
elsif @cache2_key == value
return @cache2_time
else
begin
time = @parse.call(value)
rescue => e
raise TimeParseError, "invalid time format: value = #{value}, error_class = #{e.class.name}, error = #{e.message}"
end
@cache1_key = @cache2_key
@cache1_time = @cache2_time
@cache2_key = value
@cache2_time = time
return time
end
end
alias :call :parse
end
class NumericTimeParser < TimeParser # to include TimeParseError
def initialize(type, localtime = nil, timezone = nil)
@cache1_key = @cache1_time = @cache2_key = @cache2_time = nil
if type == :unixtime
define_singleton_method(:parse, method(:parse_unixtime))
define_singleton_method(:call, method(:parse_unixtime))
else # :float
define_singleton_method(:parse, method(:parse_float))
define_singleton_method(:call, method(:parse_float))
end
end
def parse_unixtime(value)
unless value.is_a?(String) || value.is_a?(Numeric)
raise TimeParseError, "value must be a string or a number: #{value}(value.class)"
end
if @cache1_key == value
return @cache1_time
elsif @cache2_key == value
return @cache2_time
end
begin
time = Fluent::EventTime.new(value.to_i)
rescue => e
raise TimeParseError, "invalid time format: value = #{value}, error_class = #{e.class.name}, error = #{e.message}"
end
@cache1_key = @cache2_key
@cache1_time = @cache2_time
@cache2_key = value
@cache2_time = time
time
end
# rough benchmark result to compare handmade parser vs Fluent::EventTime.from_time(Time.at(value.to_r))
# full: with 9-digits of nsec after dot
# msec: with 3-digits of msec after dot
# 10_000_000 times loop on MacBookAir
## parse_by_myself(full): 12.162475 sec
## parse_by_myself(msec): 15.050435 sec
## parse_by_to_r (full): 28.722362 sec
## parse_by_to_r (msec): 28.232856 sec
def parse_float(value)
unless value.is_a?(String) || value.is_a?(Numeric)
raise TimeParseError, "value must be a string or a number: #{value}(value.class)"
end
if @cache1_key == value
return @cache1_time
elsif @cache2_key == value
return @cache2_time
end
begin
sec_s, nsec_s, _ = value.to_s.split('.', 3) # throw away second-dot and later
nsec_s = nsec_s && nsec_s[0..9] || '0'
nsec_s += '0' * (9 - nsec_s.size) if nsec_s.size < 9
time = Fluent::EventTime.new(sec_s.to_i, nsec_s.to_i)
rescue => e
raise TimeParseError, "invalid time format: value = #{value}, error_class = #{e.class.name}, error = #{e.message}"
end
@cache1_key = @cache2_key
@cache1_time = @cache2_time
@cache2_key = value
@cache2_time = time
time
end
end
class TimeFormatter
def initialize(format = nil, localtime = true, timezone = nil)
@tc1 = 0
@tc1_str = nil
@tc2 = 0
@tc2_str = nil
strftime = format && (Strftime.new(format) rescue nil)
if format && format =~ /(^|[^%])(%%)*%L|(^|[^%])(%%)*%\d*N/
define_singleton_method(:format, method(:format_with_subsec))
define_singleton_method(:call, method(:format_with_subsec))
else
define_singleton_method(:format, method(:format_without_subsec))
define_singleton_method(:call, method(:format_without_subsec))
end
formatter = Fluent::Timezone.formatter(timezone, strftime ? strftime : format)
@format_nocache = case
when formatter then formatter
when strftime && localtime then ->(time){ strftime.exec(Time.at(time)) }
when format && localtime then ->(time){ Time.at(time).strftime(format) }
when strftime then ->(time){ strftime.exec(Time.at(time).utc) }
when format then ->(time){ Time.at(time).utc.strftime(format) }
when localtime then ->(time){ Time.at(time).iso8601 }
else ->(time){ Time.at(time).utc.iso8601 }
end
end
def format_without_subsec(time)
if @tc1 == time
return @tc1_str
elsif @tc2 == time
return @tc2_str
else
str = format_nocache(time)
if @tc1 < @tc2
@tc1 = time
@tc1_str = str
else
@tc2 = time
@tc2_str = str
end
return str
end
end
def format_with_subsec(time)
if Fluent::EventTime.eq?(@tc1, time)
return @tc1_str
elsif Fluent::EventTime.eq?(@tc2, time)
return @tc2_str
else
str = format_nocache(time)
if @tc1 < @tc2
@tc1 = time
@tc1_str = str
else
@tc2 = time
@tc2_str = str
end
return str
end
end
## Dynamically defined in #initialize
# def format(time)
# end
def format_nocache(time)
@format_nocache.call(time)
end
end
class NumericTimeFormatter < TimeFormatter
def initialize(type, localtime = nil, timezone = nil)
@cache1_key = @cache1_time = @cache2_key = @cache2_time = nil
if type == :unixtime
define_singleton_method(:format, method(:format_unixtime))
define_singleton_method(:call, method(:format_unixtime))
else # :float
define_singleton_method(:format, method(:format_float))
define_singleton_method(:call, method(:format_float))
end
end
def format_unixtime(time)
time.to_i.to_s
end
def format_float(time)
if time.is_a?(Fluent::EventTime) || time.is_a?(Time)
# 10.015 secs for 10_000_000 times call on MacBookAir
nsec_s = time.nsec.to_s
nsec_s = '0' * (9 - nsec_s.size) if nsec_s.size < 9
"#{time.sec}.#{nsec_s}"
else # integer (or float?)
time.to_f.to_s
end
end
end
end