-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathout_google_cloud.rb
2152 lines (1964 loc) · 82.8 KB
/
out_google_cloud.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2014 Google Inc. All rights reserved.
#
# 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 'cgi'
require 'erb'
require 'grpc'
require 'json'
require 'open-uri'
require 'socket'
require 'time'
require 'yaml'
require 'google/apis'
require 'google/apis/logging_v2'
require 'google/cloud/logging/v2'
require 'google/gax'
require 'google/logging/v2/logging_pb'
require 'google/logging/v2/logging_services_pb'
require 'google/logging/v2/log_entry_pb'
require 'googleauth'
require_relative 'common'
require_relative 'monitoring'
require_relative 'statusz'
module Google
module Protobuf
# Alias the has_key? method to have the same interface as a regular map.
class Map
alias key? has_key?
alias to_hash to_h
end
end
end
module Google
module Auth
# Disable gcloud lookup in googleauth to avoid picking up its project id.
module CredentialsLoader
# Set $VERBOSE to nil to mute the "already initialized constant" warnings.
warn_level = $VERBOSE
begin
$VERBOSE = nil
# These constants are used to invoke gcloud on Linux and Windows,
# respectively. Ideally, we would have overridden
# CredentialsLoader.load_gcloud_project_id, but we cannot catch it
# before it's invoked via "require 'googleauth'". So we override the
# constants instead.
GCLOUD_POSIX_COMMAND = '/bin/true'.freeze
GCLOUD_WINDOWS_COMMAND = 'cd .'.freeze
GCLOUD_CONFIG_COMMAND = ''.freeze
ensure
$VERBOSE = warn_level
end
end
end
end
# FluentLogger exposes the Fluent logger to the gRPC library.
module FluentLogger
def logger
$log # rubocop:disable Style/GlobalVars
end
end
# Define a gRPC module-level logger method before grpc/logconfig.rb loads.
module GRPC
extend FluentLogger
end
# Disable the nurse/strptime gem used by FluentD's TimeParser class in
# lib/fluent/time.rb. We found this gem to be slower than the builtin Ruby
# parser in recent versions of Ruby. Fortunately FluentD will fall back to the
# builtin parser.
require 'strptime'
# Dummy Strptime class.
class Strptime
def self.new(_)
end
end
module Fluent
# fluentd output plugin for the Stackdriver Logging API
class GoogleCloudOutput < BufferedOutput
# Constants for configuration.
module ConfigConstants
# Default values for JSON payload keys to set the "httpRequest",
# "operation", "sourceLocation", "trace" fields in the LogEntry.
DEFAULT_HTTP_REQUEST_KEY = 'httpRequest'.freeze
DEFAULT_INSERT_ID_KEY = 'logging.googleapis.com/insertId'.freeze
DEFAULT_LABELS_KEY = 'logging.googleapis.com/labels'.freeze
DEFAULT_OPERATION_KEY = 'logging.googleapis.com/operation'.freeze
DEFAULT_SOURCE_LOCATION_KEY =
'logging.googleapis.com/sourceLocation'.freeze
DEFAULT_SPAN_ID_KEY = 'logging.googleapis.com/spanId'.freeze
DEFAULT_TRACE_KEY = 'logging.googleapis.com/trace'.freeze
DEFAULT_TRACE_SAMPLED_KEY = 'logging.googleapis.com/trace_sampled'.freeze
end
# Internal constants.
module InternalConstants
CREDENTIALS_PATH_ENV_VAR = 'GOOGLE_APPLICATION_CREDENTIALS'.freeze
DEFAULT_LOGGING_API_URL = 'https://logging.googleapis.com'.freeze
# The label name of local_resource_id in the json payload. When a record
# has this field in the payload, we will use the value to retrieve
# monitored resource from Stackdriver Metadata agent.
LOCAL_RESOURCE_ID_KEY = 'logging.googleapis.com/local_resource_id'.freeze
# The regexp matches stackdriver trace id format: 32-byte hex string.
# The format is documented in
# https://cloud.google.com/trace/docs/reference/v2/rpc/google.devtools.cloudtrace.v1#trace
STACKDRIVER_TRACE_ID_REGEXP = Regexp.new('^\h{32}$').freeze
# Map from each field name under LogEntry to corresponding variables
# required to perform field value extraction from the log record.
LOG_ENTRY_FIELDS_MAP = {
'http_request' => [
# The config to specify label name for field extraction from record.
'@http_request_key',
# Map from subfields' names to their types.
[
# subfield key in the payload, destination key, cast lambda (opt)
%w(cacheFillBytes cache_fill_bytes parse_int),
%w(cacheHit cache_hit parse_bool),
%w(cacheLookup cache_lookup parse_bool),
%w(cacheValidatedWithOriginServer
cache_validated_with_origin_server parse_bool),
%w(latency latency parse_latency),
%w(protocol protocol parse_string),
%w(referer referer parse_string),
%w(remoteIp remote_ip parse_string),
%w(responseSize response_size parse_int),
%w(requestMethod request_method parse_string),
%w(requestSize request_size parse_int),
%w(requestUrl request_url parse_string),
%w(serverIp server_ip parse_string),
%w(status status parse_int),
%w(userAgent user_agent parse_string)
],
# The grpc version class name.
'Google::Logging::Type::HttpRequest',
# The non-grpc version class name.
'Google::Apis::LoggingV2::HttpRequest'
],
'operation' => [
'@operation_key',
[
%w(id id parse_string),
%w(producer producer parse_string),
%w(first first parse_bool),
%w(last last parse_bool)
],
'Google::Logging::V2::LogEntryOperation',
'Google::Apis::LoggingV2::LogEntryOperation'
],
'source_location' => [
'@source_location_key',
[
%w(file file parse_string),
%w(function function parse_string),
%w(line line parse_int)
],
'Google::Logging::V2::LogEntrySourceLocation',
'Google::Apis::LoggingV2::LogEntrySourceLocation'
]
}.freeze
# The name of the WriteLogEntriesPartialErrors field in the error details.
PARTIAL_ERROR_FIELD =
'type.googleapis.com/google.logging.v2.WriteLogEntriesPartialErrors' \
.freeze
end
include Common::ServiceConstants
include self::ConfigConstants
include self::InternalConstants
Fluent::Plugin.register_output('google_cloud', self)
helpers :server, :timer
PLUGIN_NAME = 'Fluentd Google Cloud Logging plugin'.freeze
# Follows semver.org format.
PLUGIN_VERSION = begin
# Extract plugin version from file path.
match_data = __FILE__.match(
%r{fluent-plugin-google-cloud-(?<version>[^/]*)/})
if match_data
match_data['version']
else
# Extract plugin version by finding the spec this file was loaded from.
dependency = Gem::Dependency.new('fluent-plugin-google-cloud')
all_specs, = Gem::SpecFetcher.fetcher.spec_for_dependency(dependency)
matching_version, = all_specs.grep(
proc { |spec,| __FILE__.include?(spec.full_gem_path) }) do |spec,|
spec.version.to_s
end
# If no matching version was found, return a valid but obviously wrong
# value.
matching_version || '0.0.0-unknown'
end
end.freeze
# Disable this warning to conform to fluentd config_param conventions.
# rubocop:disable Style/HashSyntax
# Specify project/instance metadata.
#
# project_id, zone, and vm_id are required to have valid values, which
# can be obtained from the metadata service or set explicitly.
# Otherwise, the plugin will fail to initialize.
#
# Note that while 'project id' properly refers to the alphanumeric name
# of the project, the logging service will also accept the project number,
# so either one is acceptable in this context.
#
# Whether to attempt to obtain metadata from the local metadata service.
# It is safe to specify 'true' even on platforms with no metadata service.
config_param :use_metadata_service, :bool, :default => true
# A compatibility option to enable the legacy behavior of setting the AWS
# location to the availability zone rather than the region.
config_param :use_aws_availability_zone, :bool, :default => true
# These parameters override any values obtained from the metadata service.
config_param :project_id, :string, :default => nil
config_param :zone, :string, :default => nil
config_param :vm_id, :string, :default => nil
config_param :vm_name, :string, :default => nil
# Kubernetes-specific parameters, only used to override these values in
# the fallback path when the metadata agent is temporarily unavailable.
# They have to match the configuration of the metadata agent.
config_param :k8s_cluster_name, :string, :default => nil
config_param :k8s_cluster_location, :string, :default => nil
# Map keys from a JSON payload to corresponding LogEntry fields.
config_param :http_request_key, :string, :default =>
DEFAULT_HTTP_REQUEST_KEY
config_param :insert_id_key, :string, :default => DEFAULT_INSERT_ID_KEY
config_param :labels_key, :string, :default => DEFAULT_LABELS_KEY
config_param :operation_key, :string, :default => DEFAULT_OPERATION_KEY
config_param :source_location_key, :string, :default =>
DEFAULT_SOURCE_LOCATION_KEY
config_param :span_id_key, :string, :default => DEFAULT_SPAN_ID_KEY
config_param :trace_key, :string, :default => DEFAULT_TRACE_KEY
config_param :trace_sampled_key, :string, :default =>
DEFAULT_TRACE_SAMPLED_KEY
# Whether to try to detect if the record is a text log entry with JSON
# content that needs to be parsed.
config_param :detect_json, :bool, :default => false
# TODO(igorpeshansky): Add a parameter for the text field in the payload.
# Whether to try to detect if the VM is owned by a "subservice" such as App
# Engine of Kubernetes, rather than just associating the logs with the
# compute service of the platform. This currently only has any effect when
# running on GCE.
#
# The initial motivation for this is to separate out Kubernetes node
# component (Kubelet, etc.) logs from container logs.
config_param :detect_subservice, :bool, :default => true
# The subservice_name overrides the subservice detection, if provided.
config_param :subservice_name, :string, :default => nil
# Whether to reject log entries with invalid tags. If this option is set to
# false, tags will be made valid by converting any non-string tag to a
# string, and sanitizing any non-utf8 or other invalid characters.
config_param :require_valid_tags, :bool, :default => false
# The regular expression to use on Kubernetes logs to extract some basic
# information about the log source. The regexp must contain capture groups
# for pod_name, namespace_name, and container_name.
config_param :kubernetes_tag_regexp, :string, :default =>
'\.(?<pod_name>[^_]+)_(?<namespace_name>[^_]+)_(?<container_name>.+)$'
# label_map (specified as a JSON object) is an unordered set of fluent
# field names whose values are sent as labels rather than as part of the
# struct payload.
#
# Each entry in the map is a {"field_name": "label_name"} pair. When
# the "field_name" (as parsed by the input plugin) is encountered, a label
# with the corresponding "label_name" is added to the log entry. The
# value of the field is used as the value of the label.
#
# The map gives the user additional flexibility in specifying label
# names, including the ability to use characters which would not be
# legal as part of fluent field names.
#
# Example:
# label_map {
# "field_name_1": "sent_label_name_1",
# "field_name_2": "some.prefix/sent_label_name_2"
# }
config_param :label_map, :hash, :default => nil
# labels (specified as a JSON object) is a set of custom labels
# provided at configuration time. It allows users to inject extra
# environmental information into every message or to customize
# labels otherwise detected automatically.
#
# Each entry in the map is a {"label_name": "label_value"} pair.
#
# Example:
# labels {
# "label_name_1": "label_value_1",
# "label_name_2": "label_value_2"
# }
config_param :labels, :hash, :default => nil
# Whether to use gRPC instead of REST/JSON to communicate to the
# Stackdriver Logging API.
config_param :use_grpc, :bool, :default => false
# Whether to enable gRPC compression when communicating with the Stackdriver
# Logging API. Only used if 'use_grpc' is set to true.
config_param :grpc_compression_algorithm, :enum,
list: [:none, :gzip],
:default => nil
# Whether valid entries should be written even if some other entries fail
# due to INVALID_ARGUMENT or PERMISSION_DENIED errors when communicating to
# the Stackdriver Logging API. This flag is no longer used, and is kept for
# backwards compatibility, partial_success is enabled for all requests.
# TODO: Breaking change. Remove this flag in Logging Agent 2.0.0 release.
config_param :partial_success, :bool,
:default => true,
:skip_accessor => true,
:deprecated => 'This feature is permanently enabled'
# Whether to allow non-UTF-8 characters in user logs. If set to true, any
# non-UTF-8 character would be replaced by the string specified by
# 'non_utf8_replacement_string'. If set to false, any non-UTF-8 character
# would trigger the plugin to error out.
config_param :coerce_to_utf8, :bool, :default => true
# If 'coerce_to_utf8' is set to true, any non-UTF-8 character would be
# replaced by the string specified here.
config_param :non_utf8_replacement_string, :string, :default => ' '
# DEPRECATED: The following parameters, if present in the config
# indicate that the plugin configuration must be updated.
config_param :auth_method, :string, :default => nil
config_param :private_key_email, :string, :default => nil
config_param :private_key_path, :string, :default => nil
config_param :private_key_passphrase, :string,
:default => nil,
:secret => true
# The URL of Stackdriver Logging API. Right now this only works with the
# gRPC path (use_grpc = true). An unsecured channel is used if the URL
# scheme is 'http' instead of 'https'. One common use case of this config is
# to provide a mocked / stubbed Logging API, e.g., http://localhost:52000.
config_param :logging_api_url, :string, :default => DEFAULT_LOGGING_API_URL
# Whether to collect metrics about the plugin usage. The mechanism for
# collecting and exposing metrics is controlled by the monitoring_type
# parameter.
config_param :enable_monitoring, :bool, :default => false
# What system to use when collecting metrics. Possible values are:
# - 'prometheus', in this case default registry in the Prometheus
# client library is used, without actually exposing the endpoint
# to serve metrics in the Prometheus format.
# - 'opencensus', in this case the OpenCensus implementation is
# used to send metrics directly to Google Cloud Monitoring.
# - any other value will result in the absence of metrics.
config_param :monitoring_type, :string,
:default => Monitoring::PrometheusMonitoringRegistry.name
# The monitored resource to use for OpenCensus metrics. Only valid
# when monitoring_type is set to 'opencensus'. This value is a hash in
# the form:
# {"type":"gce_instance","labels":{"instance_id":"aaa","zone":"bbb"} (JSON)
# or type:gce_instance,labels.instance_id:aaa,labels.zone:bbb (Hash)
config_param :metrics_resource, :hash,
:symbolize_keys => true, :default => nil
# Whether to call metadata agent to retrieve monitored resource. This flag
# is kept for backwards compatibility, and is no longer used.
# TODO: Breaking change. Remove this flag in Logging Agent 2.0.0 release.
config_param :enable_metadata_agent, :bool,
:default => false,
:skip_accessor => true,
:deprecated => 'This feature is permanently disabled'
# The URL of the Metadata Agent. This flag is kept for backwards
# compatibility, and is no longer used.
# TODO: Breaking change. Remove this flag in Logging Agent 2.0.0 release.
config_param :metadata_agent_url, :string,
:default => nil,
:skip_accessor => true,
:deprecated => 'This feature is permanently disabled'
# Whether to split log entries with different log tags into different
# requests when talking to Stackdriver Logging API.
config_param :split_logs_by_tag, :bool, :default => false
# Whether to attempt adjusting invalid log entry timestamps.
config_param :adjust_invalid_timestamps, :bool, :default => true
# Whether to autoformat value of "logging.googleapis.com/trace" to
# comply with Stackdriver Trace format
# "projects/[PROJECT-ID]/traces/[TRACE-ID]" when setting
# LogEntry.trace.
config_param :autoformat_stackdriver_trace, :bool, :default => true
# Port for web server that exposes a /statusz endpoint with
# diagnostic information in HTML format. If the value is 0,
# the server is not created.
config_param :statusz_port, :integer, :default => 0
# Override for the Google Cloud Monitoring service hostname, or
# `nil` to leave as the default.
config_param :gcm_service_address, :string, :default => nil
# rubocop:enable Style/HashSyntax
# TODO: Add a log_name config option rather than just using the tag?
# Expose attr_readers to make testing of metadata more direct than only
# testing it indirectly through metadata sent with logs.
attr_reader :project_id
attr_reader :zone
attr_reader :vm_id
attr_reader :resource
attr_reader :common_labels
attr_reader :monitoring_resource
def initialize
super
# use the global logger
@log = $log # rubocop:disable Style/GlobalVars
@failed_requests_count = nil
@successful_requests_count = nil
@dropped_entries_count = nil
@ingested_entries_count = nil
@retried_entries_count = nil
@ok_code = nil
@uptime_update_time = Time.now.to_i
end
def configure(conf)
super
# TODO(qingling128): Remove this warning after the support is added. Also
# remove the comment in the description of this configuration.
unless @logging_api_url == DEFAULT_LOGGING_API_URL || @use_grpc
@log.warn 'Detected customized logging_api_url while use_grpc is not' \
' enabled. Customized logging_api_url for the non-gRPC path' \
' is not supported. The logging_api_url option will be' \
' ignored.'
end
# Alert on old authentication configuration.
unless @auth_method.nil? && @private_key_email.nil? &&
@private_key_path.nil? && @private_key_passphrase.nil?
extra = []
extra << 'auth_method' unless @auth_method.nil?
extra << 'private_key_email' unless @private_key_email.nil?
extra << 'private_key_path' unless @private_key_path.nil?
extra << 'private_key_passphrase' unless @private_key_passphrase.nil?
raise Fluent::ConfigError,
"#{PLUGIN_NAME} no longer supports auth_method.\n" \
"Please remove configuration parameters: #{extra.join(' ')}"
end
set_regexp_patterns
@utils = Common::Utils.new(@log)
@platform = @utils.detect_platform(@use_metadata_service)
# Treat an empty setting of the credentials file path environment variable
# as unset. This way the googleauth lib could fetch the credentials
# following the fallback path.
ENV.delete(CREDENTIALS_PATH_ENV_VAR) if
ENV[CREDENTIALS_PATH_ENV_VAR] == ''
# Set required variables: @project_id, @vm_id, @vm_name and @zone.
@project_id = @utils.get_project_id(@platform, @project_id)
@vm_id = @utils.get_vm_id(@platform, @vm_id)
@vm_name = @utils.get_vm_name(@vm_name)
@zone = @utils.get_location(@platform, @zone, @use_aws_availability_zone)
# All metadata parameters must now be set.
@utils.check_required_metadata_variables(
@platform, @project_id, @zone, @vm_id)
# Retrieve monitored resource.
# Fail over to retrieve monitored resource via the legacy path if we fail
# to get it from Metadata Agent.
@resource ||= @utils.determine_agent_level_monitored_resource_via_legacy(
@platform, @subservice_name, @detect_subservice, @vm_id, @zone)
if @metrics_resource
unless @metrics_resource[:type].is_a?(String)
raise Fluent::ConfigError,
'metrics_resource.type must be a string:' \
" #{@metrics_resource}."
end
if @metrics_resource.key?(:labels)
unless @metrics_resource[:labels].is_a?(Hash)
raise Fluent::ConfigError,
'metrics_resource.labels must be a hash:' \
" #{@metrics_resource}."
end
extra_keys = @metrics_resource.reject do |k, _|
k == :type || k == :labels
end
unless extra_keys.empty?
raise Fluent::ConfigError,
"metrics_resource has unrecognized keys: #{extra_keys.keys}."
end
else
extra_keys = @metrics_resource.reject do |k, _|
k == :type || k.to_s.start_with?('labels.')
end
unless extra_keys.empty?
raise Fluent::ConfigError,
"metrics_resource has unrecognized keys: #{extra_keys.keys}."
end
# Transform the Hash form of the metrics_resource config if necessary.
resource_type = @metrics_resource[:type]
resource_labels = @metrics_resource.each_with_object({}) \
do |(k, v), h|
h[k.to_s.sub('labels.', '')] = v if k.to_s.start_with? 'labels.'
end
@metrics_resource = { type: resource_type, labels: resource_labels }
end
end
# If monitoring is enabled, register metrics in the default registry
# and store metric objects for future use.
if @enable_monitoring
unless Monitoring::MonitoringRegistryFactory.supports_monitoring_type(
@monitoring_type)
@log.warn "monitoring_type '#{@monitoring_type}' is unknown; "\
'there will be no metrics'
end
if @metrics_resource
@monitoring_resource = @utils.create_monitored_resource(
@metrics_resource[:type], @metrics_resource[:labels])
else
@monitoring_resource = @resource
end
@registry = Monitoring::MonitoringRegistryFactory
.create(@monitoring_type, @project_id,
@monitoring_resource, @gcm_service_address)
# Export metrics every 60 seconds.
timer_execute(:export_metrics, 60) { @registry.export }
# Uptime should be a gauge, but the metric definition is a counter and
# we can't change it.
@uptime_metric = @registry.counter(
:uptime, [:version], 'Uptime of Logging agent',
'agent.googleapis.com/agent', 'CUMULATIVE')
update_uptime
timer_execute(:update_uptime, 1) { update_uptime }
@successful_requests_count = @registry.counter(
:stackdriver_successful_requests_count,
[:grpc, :code],
'A number of successful requests to the Stackdriver Logging API',
'agent.googleapis.com/agent', 'CUMULATIVE')
@failed_requests_count = @registry.counter(
:stackdriver_failed_requests_count,
[:grpc, :code],
'A number of failed requests to the Stackdriver Logging '\
'API, broken down by the error code',
'agent.googleapis.com/agent', 'CUMULATIVE')
@ingested_entries_count = @registry.counter(
:stackdriver_ingested_entries_count,
[:grpc, :code],
'A number of log entries ingested by Stackdriver Logging',
'agent.googleapis.com/agent', 'CUMULATIVE')
@dropped_entries_count = @registry.counter(
:stackdriver_dropped_entries_count,
[:grpc, :code],
'A number of log entries dropped by the Stackdriver output plugin',
'agent.googleapis.com/agent', 'CUMULATIVE')
@retried_entries_count = @registry.counter(
:stackdriver_retried_entries_count,
[:grpc, :code],
'The number of log entries that failed to be ingested by '\
'the Stackdriver output plugin due to a transient error '\
'and were retried',
'agent.googleapis.com/agent', 'CUMULATIVE')
@ok_code = @use_grpc ? GRPC::Core::StatusCodes::OK : 200
end
# Set regexp that we should match tags against later on. Using a list
# instead of a map to ensure order.
@tag_regexp_list = []
if @resource.type == GKE_CONSTANTS[:resource_type]
@tag_regexp_list << [
GKE_CONSTANTS[:resource_type], @compiled_kubernetes_tag_regexp
]
end
# Determine the common labels that should be added to all log entries
# processed by this logging agent.
@common_labels = determine_agent_level_common_labels(@resource)
# The resource and labels are now set up; ensure they can't be modified
# without first duping them.
@resource.freeze
@resource.labels.freeze
@common_labels.freeze
if @use_grpc
@construct_log_entry = method(:construct_log_entry_in_grpc_format)
@write_request = method(:write_request_via_grpc)
else
@construct_log_entry = method(:construct_log_entry_in_rest_format)
@write_request = method(:write_request_via_rest)
end
if [Common::Platform::GCE, Common::Platform::EC2].include?(@platform)
# Log an informational message containing the Logs viewer URL
@log.info 'Logs viewer address: https://console.cloud.google.com/logs/',
"viewer?project=#{@project_id}&resource=#{@resource.type}/",
"instance_id/#{@vm_id}"
end
end
def start
super
init_api_client
@successful_call = false
@timenanos_warning = false
if @statusz_port > 0
@log.info "Starting statusz server on port #{@statusz_port}"
server_create(:out_google_cloud_statusz,
@statusz_port,
bind: '127.0.0.1') do |data, conn|
if data.split(' ')[1] == '/statusz'
write_html_response(data, conn, 200, Statusz.response(self))
else
write_html_response(data, conn, 404, "Not found\n")
end
end
end
end
def shutdown
super
# Export metrics on shutdown. This is a best-effort attempt, and it might
# fail, for instance if there was a recent write to the same time series.
@registry.export unless @registry.nil?
end
def write(chunk)
grouped_entries = group_log_entries_by_tag_and_local_resource_id(chunk)
requests_to_send = []
grouped_entries.each do |(tag, local_resource_id), arr|
entries = []
group_level_resource, group_level_common_labels =
determine_group_level_monitored_resource_and_labels(
tag, local_resource_id)
arr.each do |time, record|
entry_level_resource, entry_level_common_labels =
determine_entry_level_monitored_resource_and_labels(
group_level_resource, group_level_common_labels, record)
is_json = false
if @detect_json
# Save the following fields if available, then clear them out to
# allow for determining whether we should parse the log or message
# field.
# This list should be in sync with
# https://cloud.google.com/logging/docs/agent/configuration#special-fields.
preserved_keys = [
'time',
'timeNanos',
'timestamp',
'timestampNanos',
'timestampSeconds',
'severity',
@http_request_key,
@insert_id_key,
@labels_key,
@operation_key,
@source_location_key,
@span_id_key,
@trace_key,
@trace_sampled_key
]
# If the log is json, we want to export it as a structured log
# unless there is additional metadata that would be lost.
record_json = nil
if (record.keys - preserved_keys).length == 1
%w(log message msg).each do |field|
if record.key?(field)
record_json = parse_json_or_nil(record[field])
end
end
end
unless record_json.nil?
# Propagate these if necessary. Note that we don't want to
# override these keys in the JSON we've just parsed.
preserved_keys.each do |key|
record_json[key] ||= record[key] if
record.key?(key) && !record_json.key?(key)
end
record = record_json
is_json = true
end
end
ts_secs, ts_nanos, timestamp = compute_timestamp(record, time)
ts_secs, ts_nanos = adjust_timestamp_if_invalid(timestamp, Time.now) \
if @adjust_invalid_timestamps && timestamp
severity = compute_severity(
entry_level_resource.type, record, entry_level_common_labels)
dynamic_labels_from_payload = parse_labels(record)
entry_level_common_labels = entry_level_common_labels.merge!(
dynamic_labels_from_payload) if dynamic_labels_from_payload
entry = @construct_log_entry.call(entry_level_common_labels,
entry_level_resource,
severity,
ts_secs,
ts_nanos)
insert_id = record.delete(@insert_id_key)
entry.insert_id = insert_id if insert_id
span_id = record.delete(@span_id_key)
entry.span_id = span_id if span_id
trace = record.delete(@trace_key)
entry.trace = compute_trace(trace) if trace
trace_sampled = record.delete(@trace_sampled_key)
entry.trace_sampled = parse_bool(trace_sampled) unless
trace_sampled.nil?
set_log_entry_fields(record, entry)
set_payload(entry_level_resource.type, record, entry, is_json)
entries.push(entry)
end
# Don't send an empty request if we rejected all the entries.
next if entries.empty?
log_name = "projects/#{@project_id}/logs/#{log_name(
tag, group_level_resource)}"
requests_to_send << {
entries: entries,
log_name: log_name,
resource: group_level_resource,
labels: group_level_common_labels
}
end
if @split_logs_by_tag
requests_to_send.each do |request|
@write_request.call(request)
end
else
# Combine all requests into one. The request level "log_name" will be
# ported to the entry level. The request level "resource" and "labels"
# are ignored as they should have been folded into the entry level
# "resource" and "labels" already anyway.
combined_entries = []
requests_to_send.each do |request|
request[:entries].each do |entry|
# Modify entries in-place as they are not needed later on.
entry.log_name = request[:log_name]
end
combined_entries.concat(request[:entries])
end
@write_request.call(entries: combined_entries) unless
combined_entries.empty?
end
end
def multi_workers_ready?
true
end
def self.version_string
@version_string ||= "google-fluentd/#{PLUGIN_VERSION}"
end
def update_uptime
now = Time.now.to_i
@uptime_metric.increment(
by: now - @uptime_update_time,
labels: { version: Fluent::GoogleCloudOutput.version_string })
@uptime_update_time = now
end
private
def write_html_response(data, conn, code, response)
@log.info "#{conn.remote_host} - - " \
"#{Time.now.strftime('%d/%b/%Y:%H:%M:%S %z')} " \
"\"#{data.lines.first.strip}\" #{code} #{response.bytesize}"
conn.write "HTTP/1.1 #{code}\r\n"
conn.write "Content-Type: text/html\r\n"
conn.write "Content-Length: #{response.bytesize}\r\n"
conn.write "\r\n"
conn.write response
end
def compute_trace(trace)
return trace unless @autoformat_stackdriver_trace &&
STACKDRIVER_TRACE_ID_REGEXP.match(trace)
"projects/#{@project_id}/traces/#{trace}"
end
def construct_log_entry_in_grpc_format(labels,
resource,
severity,
ts_secs,
ts_nanos)
entry = Google::Logging::V2::LogEntry.new(
labels: labels,
resource: Google::Api::MonitoredResource.new(
type: resource.type,
labels: resource.labels.to_h
),
severity: grpc_severity(severity)
)
# If "seconds" is null or not an integer, we will omit the timestamp
# field and defer the decision on how to handle it to the downstream
# Logging API. If "nanos" is null or not an integer, it will be set
# to 0.
if ts_secs.is_a?(Integer)
ts_nanos = 0 unless ts_nanos.is_a?(Integer)
entry.timestamp = Google::Protobuf::Timestamp.new(
seconds: ts_secs,
nanos: ts_nanos
)
end
entry
end
def construct_log_entry_in_rest_format(labels,
resource,
severity,
ts_secs,
ts_nanos)
# Remove the labels if we didn't populate them with anything.
resource.labels = nil if resource.labels.empty?
Google::Apis::LoggingV2::LogEntry.new(
labels: labels,
resource: resource,
severity: severity,
timestamp: {
seconds: ts_secs,
nanos: ts_nanos
}
)
end
def write_request_via_grpc(entries:,
log_name: '',
resource: nil,
labels: {})
client = api_client
entries_count = entries.length
client.write_log_entries(
entries,
log_name: log_name,
# Leave resource nil if it's nil.
resource: if resource
Google::Api::MonitoredResource.new(
type: resource.type,
labels: resource.labels.to_h
)
end,
labels: labels.map do |k, v|
[k.encode('utf-8'), convert_to_utf8(v)]
end.to_h,
partial_success: true
)
increment_successful_requests_count
increment_ingested_entries_count(entries_count)
# Let the user explicitly know when the first call succeeded, to
# aid with verification and troubleshooting.
unless @successful_call
@successful_call = true
@log.info 'Successfully sent gRPC to Stackdriver Logging API.'
end
rescue Google::Gax::GaxError => gax_error
# GRPC::BadStatus is wrapped in error.cause.
error = gax_error.cause
# See the mapping between HTTP status and gRPC status code at:
# https://github.com/grpc/grpc/blob/master/src/core/lib/transport/status_conversion.cc
case error
# Server error, so retry via re-raising the error.
when \
# HTTP status 500 (Internal Server Error).
GRPC::Internal,
# HTTP status 501 (Not Implemented).
GRPC::Unimplemented,
# HTTP status 503 (Service Unavailable).
GRPC::Unavailable,
# HTTP status 504 (Gateway Timeout).
GRPC::DeadlineExceeded
increment_retried_entries_count(entries_count, error.code)
@log.debug "Retrying #{entries_count} log message(s) later.",
error: error.to_s, error_code: error.code.to_s
raise error
# Most client errors indicate a problem with the request itself and
# should not be retried.
when \
# HTTP status 401 (Unauthorized).
# These are usually solved via a `gcloud auth` call, or by modifying
# the permissions on the Google Cloud project.
GRPC::Unauthenticated,
# HTTP status 404 (Not Found).
GRPC::NotFound,
# HTTP status 409 (Conflict).
GRPC::Aborted,
# HTTP status 412 (Precondition Failed).
GRPC::FailedPrecondition,
# HTTP status 429 (Too Many Requests).
GRPC::ResourceExhausted,
# HTTP status 499 (Client Closed Request).
GRPC::Cancelled,
# the remaining http codes in both 4xx and 5xx category.
# It's debatable whether to retry or drop these log entries.
# This decision is made to avoid retrying forever due to
# client errors.
GRPC::Unknown
increment_failed_requests_count(error.code)
increment_dropped_entries_count(entries_count, error.code)
@log.warn "Dropping #{entries_count} log message(s)",
error: error.to_s, error_code: error.code.to_s
# As partial_success is enabled, valid entries should have been
# written even if some other entries fail due to InvalidArgument or
# PermissionDenied errors. Only invalid entries will be dropped.
when \
# HTTP status 400 (Bad Request).
GRPC::InvalidArgument,
# HTTP status 403 (Forbidden).
GRPC::PermissionDenied
error_details_map = construct_error_details_map_grpc(gax_error)
if error_details_map.empty?
increment_failed_requests_count(error.code)
increment_dropped_entries_count(entries_count, error.code)
@log.warn "Dropping #{entries_count} log message(s)",
error: error.to_s, error_code: error.code.to_s
else
error_details_map.each do |(error_code, error_message), indexes|
partial_errors_count = indexes.length
increment_dropped_entries_count(partial_errors_count,
error_code)
entries_count -= partial_errors_count
@log.warn "Dropping #{partial_errors_count} log message(s)",
error: error_message, error_code: error_code.to_s
end
# Consider partially successful requests successful.
increment_successful_requests_count
increment_ingested_entries_count(entries_count)
end
else
# Assume it's a problem with the request itself and don't retry.
error_code = if error.respond_to?(:code)
error.code
else
GRPC::Core::StatusCodes::UNKNOWN
end
increment_failed_requests_count(error_code)
increment_dropped_entries_count(entries_count, error_code)
@log.error "Unknown response code #{error_code} from the server," \
" dropping #{entries_count} log message(s)",
error: error.to_s, error_code: error_code.to_s
end
# Got an unexpected error (not Google::Gax::GaxError) from the
# google-cloud-logging lib.
rescue StandardError => error
increment_failed_requests_count(GRPC::Core::StatusCodes::UNKNOWN)
increment_dropped_entries_count(entries_count,