Created
February 13, 2017 19:26
-
-
Save pior/6ffb92c74e3ba02c192d8854e6706a3c to your computer and use it in GitHub Desktop.
Simple ruby lib for Google Cloud Trace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'securerandom' | |
| require 'date' | |
| require 'googleauth' | |
| require 'google/apis/cloudtrace_v1' | |
| class CloudTrace | |
| def initialize(project_id) | |
| @project_id = project_id | |
| end | |
| def start(span_name) | |
| @recorder = SpanRecorder.new(span_name) | |
| end | |
| def with_span(span_name) | |
| @recorder.with_span(span_name) { yield } | |
| end | |
| def publish | |
| spans = @recorder.spans | |
| spans.each { |s| puts s.inspect } | |
| trace = Google::Apis::CloudtraceV1::Trace.new(trace_id: new_trace_id, project_id: @project_id, spans: spans) | |
| traces = Google::Apis::CloudtraceV1::Traces.new(traces: [trace]) | |
| service.patch_project_traces(@project_id, traces) | |
| end | |
| private | |
| def new_trace_id | |
| SecureRandom.uuid.split('-').join | |
| end | |
| def service | |
| service = Google::Apis::CloudtraceV1::CloudTraceService.new | |
| service.authorization = Google::Auth.get_application_default(['https://www.googleapis.com/auth/trace.append']) | |
| service | |
| end | |
| end | |
| class SpanRecorder | |
| def initialize(trace_name) | |
| @trace_name = trace_name | |
| @next_span_id = 0 | |
| @mutex = Mutex.new | |
| @master_span = Google::Apis::CloudtraceV1::TraceSpan.new( | |
| name: @trace_name, | |
| span_id: next_span_id, | |
| start_time: now, | |
| end_time: nil, | |
| labels: {}, | |
| kind: 'RPC_SERVER', | |
| ) | |
| @spans = [] | |
| end | |
| def with_span(span_name) | |
| start_time = now | |
| yield | |
| @spans << Google::Apis::CloudtraceV1::TraceSpan.new( | |
| name: span_name, | |
| span_id: next_span_id, | |
| parent_span_id: @master_span.span_id, | |
| start_time: start_time, | |
| end_time: now, | |
| labels: {}, | |
| kind: 'RPC_CLIENT', | |
| ) | |
| end | |
| def spans | |
| @master_span.end_time = now | |
| [@master_span, *@spans] | |
| end | |
| private | |
| def next_span_id | |
| @mutex.synchronize { @next_span_id += 1 } | |
| @next_span_id.to_s | |
| end | |
| def now | |
| Time.now.utc.round(10).iso8601(6) | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment