25 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/aggregation/last_value.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | module OpenCensus
5 | module Stats
6 | module Aggregation
7 | # Last value aggregation type
8 | class LastValue
9 | # Create new aggregation data container to store last value.
10 | # values.
11 | # @return [AggregationData::LastValue]
12 | def create_aggregation_data
13 | AggregationData::LastValue.new
14 | end
15 | end
16 | end
17 | end
18 | end
19 |
--------------------------------------------------------------------------------
/test/stats/aggregation/sum_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Stats::Aggregation::Sum do
4 | describe "create_aggregation_data" do
5 | it "create sum aggregation data instance with default value" do
6 | sum_aggregation = OpenCensus::Stats::Aggregation::Sum.new
7 | aggregation_data = sum_aggregation.create_aggregation_data
8 | aggregation_data.must_be_kind_of OpenCensus::Stats::AggregationData::Sum
9 | aggregation_data.value.must_equal 0
10 | end
11 | end
12 | end
13 |
--------------------------------------------------------------------------------
/test/stats/aggregation/count_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Stats::Aggregation::Count do
4 | describe "create_aggregation_data" do
5 | it "create count aggregation data instance with default value" do
6 | count_aggregation = OpenCensus::Stats::Aggregation::Count.new
7 | aggregation_data = count_aggregation.create_aggregation_data
8 | aggregation_data.must_be_kind_of OpenCensus::Stats::AggregationData::Count
9 | aggregation_data.value.must_equal 0
10 | end
11 | end
12 | end
13 |
--------------------------------------------------------------------------------
/test/tags_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Tags do
4 | before{
5 | OpenCensus::Tags.unset_tag_map_context
6 | }
7 |
8 | it "can be set and unset tag map context" do
9 | tag_map = OpenCensus::Tags::TagMap.new({ "frontend" => "mobile-1.0"})
10 | OpenCensus::Tags.tag_map_context.must_be_nil
11 | OpenCensus::Tags.tag_map_context = tag_map
12 | OpenCensus::Tags.tag_map_context.must_equal tag_map
13 | OpenCensus::Tags.unset_tag_map_context
14 | OpenCensus::Tags.tag_map_context.must_be_nil
15 | end
16 | end
17 |
--------------------------------------------------------------------------------
/test/stats/aggregation/last_value_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Stats::Aggregation::LastValue do
4 | describe "create_aggregation_data" do
5 | it "create last value aggregation data instance with default value" do
6 | last_value_aggregation = OpenCensus::Stats::Aggregation::LastValue.new
7 | aggregation_data = last_value_aggregation.create_aggregation_data
8 | aggregation_data.must_be_kind_of OpenCensus::Stats::AggregationData::LastValue
9 | aggregation_data.value.must_be_nil
10 | end
11 | end
12 | end
13 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | require "bundler/gem_tasks"
2 | require "rake/testtask"
3 | require "yard"
4 |
5 | require "rubocop/rake_task"
6 | RuboCop::RakeTask.new
7 |
8 | Rake::TestTask.new :test do |t|
9 | t.libs << "test"
10 | t.libs << "lib"
11 | t.test_files = FileList["test/**/*_test.rb"]
12 | end
13 |
14 | YARD::Rake::YardocTask.new do |t|
15 | t.files = ['lib/**/*.rb'] # optional
16 | t.options = ['--output-dir', 'docs/api'] # optional
17 | t.stats_options = ['--list-undoc'] # optional
18 | end
19 |
20 | task :faster do
21 | ENV["FASTER_TESTS"] = "true"
22 | end
23 |
24 | task :default => [:test, :rubocop, :yard]
25 |
--------------------------------------------------------------------------------
/test/stats/aggregation_data/count_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Stats::AggregationData::Count do
4 | it "create count aggregation data with default value" do
5 | aggregation_data = OpenCensus::Stats::AggregationData::Count.new
6 | aggregation_data.value.must_equal 0
7 | end
8 |
9 | describe "add" do
10 | it "add value" do
11 | aggregation_data = OpenCensus::Stats::AggregationData::Count.new
12 |
13 | time = Time.now
14 | aggregation_data.add nil, time
15 | aggregation_data.value.must_equal 1
16 | aggregation_data.time.must_equal time
17 | end
18 | end
19 | end
20 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/aggregation_data.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | require "opencensus/stats/aggregation_data/sum"
5 | require "opencensus/stats/aggregation_data/count"
6 | require "opencensus/stats/aggregation_data/last_value"
7 | require "opencensus/stats/aggregation_data/distribution"
8 |
9 | module OpenCensus
10 | module Stats
11 | # # AggregationData
12 | #
13 | # AggregationData to store collected stats data.
14 | # Aggregation data container type:
15 | # - Sum
16 | # - Count
17 | # - Last Value
18 | # - Distribution - calcualate sum, count, min, max, mean,
19 | # sum of squared deviation
20 | #
21 | module AggregationData
22 | end
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/lib/opencensus/version.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | module OpenCensus
17 | ## Current OpenCensus version
18 | VERSION = "0.5.0".freeze
19 | end
20 |
--------------------------------------------------------------------------------
/test/stats/aggregation_data/sum_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Stats::AggregationData::Sum do
4 | it "create sum aggregation data with default value" do
5 | aggregation_data = OpenCensus::Stats::AggregationData::Sum.new
6 | aggregation_data.value.must_equal 0
7 | end
8 |
9 | describe "add" do
10 | it "add value" do
11 | aggregation_data = OpenCensus::Stats::AggregationData::Sum.new
12 |
13 | time = Time.now
14 | aggregation_data.add 10, time
15 | aggregation_data.value.must_equal 10
16 | aggregation_data.time.must_equal time
17 |
18 | time = Time.now
19 | aggregation_data.add 15, time
20 | aggregation_data.value.must_equal 25
21 | aggregation_data.time.must_equal time
22 | end
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/aggregation.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | require "opencensus/stats/aggregation/sum"
5 | require "opencensus/stats/aggregation/count"
6 | require "opencensus/stats/aggregation/last_value"
7 | require "opencensus/stats/aggregation/distribution"
8 | require "opencensus/stats/aggregation_data"
9 | require "opencensus/stats/exemplar"
10 |
11 | module OpenCensus
12 | module Stats
13 | # # Aggregation
14 | #
15 | # Aggregation types to describes how the data collected based on aggregation
16 | # type.
17 | # Aggregation types are.
18 | # - Sum
19 | # - Count
20 | # - Last Value
21 | # - Distribution - calcualate min, max, mean, sum, count,
22 | # sum of squared deviation
23 | #
24 | module Aggregation
25 | end
26 | end
27 | end
28 |
--------------------------------------------------------------------------------
/test/stats/aggregation_data/last_value_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Stats::AggregationData::LastValue do
4 | it "create count aggregation data with default value" do
5 | aggregation_data = OpenCensus::Stats::AggregationData::LastValue.new
6 | aggregation_data.value.must_be_nil
7 | end
8 |
9 | describe "add" do
10 | it "add value" do
11 | aggregation_data = OpenCensus::Stats::AggregationData::LastValue.new
12 |
13 | time = Time.now
14 | aggregation_data.add 1, time
15 | aggregation_data.value.must_equal 1
16 | aggregation_data.time.must_equal time
17 |
18 | time = Time.now
19 | aggregation_data.add 10, time
20 | aggregation_data.value.must_equal 10
21 | aggregation_data.time.must_equal time
22 | end
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/test/opencensus_test.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | require "test_helper"
16 |
17 | class OpenCensusTest < Minitest::Test
18 | def test_that_it_has_a_version_number
19 | refute_nil ::OpenCensus::VERSION
20 | end
21 | end
22 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/trace_context_data.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2018 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | module OpenCensus
17 | module Trace
18 | ##
19 | # Struct that holds parsed trace context data.
20 | #
21 | TraceContextData = Struct.new :trace_id, :span_id, :trace_options
22 | end
23 | end
24 |
--------------------------------------------------------------------------------
/lib/opencensus/common.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | require "opencensus/common/config"
17 |
18 | module OpenCensus
19 | ##
20 | # The Common module contains common infrastructure that can be shared between
21 | # Trace and Stats (not yet implemented)
22 | #
23 | module Common
24 | end
25 | end
26 |
--------------------------------------------------------------------------------
/test/stats/view_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Stats::View do
4 | let(:measure){
5 | OpenCensus::Stats::Measure.new(
6 | name: "latency",
7 | unit: "ms",
8 | type: OpenCensus::Stats::Measure::INT64_TYPE,
9 | description: "latency desc"
10 | )
11 | }
12 | let(:aggregation){ OpenCensus::Stats::Aggregation::Sum.new }
13 | let(:columns) { ["frontend"]}
14 |
15 | it "create view instance and populate properties" do
16 | view = OpenCensus::Stats::View.new(
17 | name: "test.view",
18 | measure: measure,
19 | aggregation: aggregation,
20 | description: "Test view",
21 | columns: columns
22 | )
23 |
24 | view.name.must_equal "test.view"
25 | view.measure.must_equal measure
26 | view.aggregation.must_equal aggregation
27 | view.description.must_equal "Test view"
28 | view.columns.must_equal columns
29 | end
30 | end
31 |
--------------------------------------------------------------------------------
/test/test_helper.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
16 | require "opencensus"
17 |
18 | require "minitest/autorun"
19 | require "minitest/focus"
20 |
21 | class TestRandom < Array
22 | alias_method :rand, :shift
23 | end
24 |
25 | class TestTimeClass < Array
26 | alias_method :now, :shift
27 | end
28 |
--------------------------------------------------------------------------------
/test/stats/exemplar_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Stats::Exemplar do
4 | describe "create" do
5 | it "create instance with attachments" do
6 | value = 100.1
7 | time = Time.now.utc
8 | attachments = { "test" => "value" }
9 |
10 | exemplar = OpenCensus::Stats::Exemplar.new(
11 | value: value,
12 | time: time,
13 | attachments: attachments
14 | )
15 |
16 | exemplar.value.must_equal value
17 | exemplar.time.must_equal time
18 | exemplar.attachments.must_equal attachments
19 | end
20 |
21 | it "attachments can not be nil" do
22 | value = 100.2
23 | time = Time.now.utc
24 | attachments = nil
25 |
26 | proc {
27 | OpenCensus::Stats::Exemplar.new(
28 | value: value,
29 | time: time,
30 | attachments: attachments
31 | )
32 | }.must_raise ArgumentError
33 | end
34 | end
35 | end
36 |
--------------------------------------------------------------------------------
/test/trace/samplers/always_sample_test.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | require "test_helper"
16 |
17 | describe OpenCensus::Trace::Samplers::AlwaysSample do
18 | let(:sampler) { OpenCensus::Trace::Samplers::AlwaysSample.new }
19 |
20 | describe ".call" do
21 | it "should always return true" do
22 | sampler.call.must_equal true
23 | end
24 | end
25 | end
26 |
--------------------------------------------------------------------------------
/test/trace/samplers/never_sample_test.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | require "test_helper"
16 |
17 | describe OpenCensus::Trace::Samplers::NeverSample do
18 | let(:sampler) { OpenCensus::Trace::Samplers::NeverSample.new }
19 |
20 | describe ".call" do
21 | it "should always return false" do
22 | sampler.call.must_equal false
23 | end
24 | end
25 | end
26 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/aggregation_data/last_value.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | module OpenCensus
5 | module Stats
6 | module AggregationData
7 | # # LastValue
8 | #
9 | # Represents the last recorded value.
10 | class LastValue
11 | # @return [Integer,Float] Last recorded value.
12 | attr_reader :value
13 |
14 | # @return [Time] The latest time at new data point was recorded
15 | attr_reader :time
16 |
17 | # rubocop:disable Lint/UnusedMethodArgument
18 |
19 | # Set last value
20 | # @param [Integer,Float] value
21 | # @param [Time] time Time of data point was recorded
22 | # @param [Hash] attachments Attachments are not in use
23 | def add value, time, attachments: nil
24 | @time = time
25 | @value = value
26 | end
27 |
28 | # rubocop:enable Lint/UnusedMethodArgument
29 | end
30 | end
31 | end
32 | end
33 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/aggregation_data/sum.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | module OpenCensus
5 | module Stats
6 | module AggregationData
7 | # Sum
8 | #
9 | # Accumulate measurement values.
10 | class Sum
11 | # @return [Integer,Float] The current sum value.
12 | attr_reader :value
13 |
14 | # @return [Time] The latest time at new data point was recorded
15 | attr_reader :time
16 |
17 | # @private
18 | def initialize
19 | @value = 0
20 | end
21 |
22 | # rubocop:disable Lint/UnusedMethodArgument
23 |
24 | # Add value
25 | # @param [Integer,Float] value
26 | # @param [Time] time Time of data point was recorded
27 | # @param [Hash] attachments Attachments are not in use.
28 | def add value, time, attachments: nil
29 | @time = time
30 | @value += value
31 | end
32 |
33 | # rubocop:enable Lint/UnusedMethodArgument
34 | end
35 | end
36 | end
37 | end
38 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/aggregation_data/count.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | module OpenCensus
5 | module Stats
6 | module AggregationData
7 | # # Count
8 | #
9 | # Counts number of measurements recorded.
10 | class Count
11 | # @return [Integer,Float] Current count value.
12 | attr_reader :value
13 |
14 | # @return [Time] The latest timestamp a new data point was recorded
15 | attr_reader :time
16 |
17 | # @private
18 | def initialize
19 | @value = 0
20 | end
21 |
22 | # rubocop:disable Lint/UnusedMethodArgument
23 |
24 | # Increment counter.
25 | # @param [Value] value
26 | # @param [Time] time Time of data point was recorded
27 | # @param [Hash] attachments Attachments are not in use.
28 | def add value, time, attachments: nil
29 | @time = time
30 | @value += 1
31 | end
32 |
33 | # rubocop:enable Lint/UnusedMethodArgument
34 | end
35 | end
36 | end
37 | end
38 |
--------------------------------------------------------------------------------
/examples/hello-world/README.md:
--------------------------------------------------------------------------------
1 | # Hello World example
2 |
3 | This example application demonstrates how to use OpenCensus to record traces for a Sinatra-based web application.
4 |
5 | ## Prerequisites
6 |
7 | Ruby 2.2 or later is required. Make sure you have Bundler installed as well.
8 |
9 | gem install bundler
10 |
11 | ## Installation
12 |
13 | Get the example from the OpenCensus Ruby repository on Github, and cd into the example application directory.
14 |
15 | git clone https://github.com/census-instrumentation/opencensus-ruby.git
16 | cd opencensus-ruby/examples/hello-world
17 |
18 | Install the dependencies using Bundler.
19 |
20 | bundle install
21 |
22 | ## Running the example
23 |
24 | Run the application locally on your workstation with:
25 |
26 | bundle exec ruby hello.rb
27 |
28 | This will run on port 4567 by default, and display application logs on the terminal. From a separate shell, you can send requests using a tool such as curl:
29 |
30 | curl http://localhost:4567/
31 | curl http://localhost:4567/lengthy
32 |
33 | The running application will log the captured traces.
34 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/integrations.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | module OpenCensus
17 | module Trace
18 | ##
19 | # The Integrations module contains implementations of integrations with
20 | # popular gems such as Rails and Faraday.
21 | #
22 | # Integrations are not loaded by default. To use an integration,
23 | # require it explicitly. e.g.:
24 | #
25 | # require "opencensus/trace/integrations/rack_middleware"
26 | #
27 | module Integrations
28 | end
29 | end
30 | end
31 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/measurement.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | module OpenCensus
5 | module Stats
6 | # Measurement
7 | #
8 | # Describes a data point to be collected for a Measure.
9 | class Measurement
10 | # @return [Measure] A measure to which the value is applied.
11 | attr_reader :measure
12 |
13 | # @return [Integer,Float] The recorded value
14 | attr_reader :value
15 |
16 | # @return [TagMap] The tags to which the value is applied
17 | attr_reader :tags
18 |
19 | # @return [Time] The time when measurement was created.
20 | attr_reader :time
21 |
22 | # Create a instance of measurement
23 | #
24 | # @param [Measure] measure A measure to which the value is applied.
25 | # @param [Integer,Float] value Measurement value.
26 | # @param [Hash] tags The tags to which the value is applied
27 | def initialize measure:, value:, tags:
28 | @measure = measure
29 | @value = value
30 | @tags = Tags::TagMap.new tags
31 | @time = Time.now.utc
32 | end
33 | end
34 | end
35 | end
36 |
--------------------------------------------------------------------------------
/examples/stats/quickstart.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | $LOAD_PATH.unshift File.expand_path("../../lib", __dir__)
4 | require "opencensus"
5 |
6 | MIB = 1 << 20
7 | fontend_key = "my.org/keys/frontend"
8 | video_size_measure = OpenCensus::Stats.measure_int(
9 | name: "my.org/measures/video_size",
10 | unit: "By",
11 | description: "size of processed videos"
12 | )
13 | video_size_distribution = OpenCensus::Stats.distribution_aggregation(
14 | [0.0, 16.0 * MIB, 256.0 * MIB]
15 | )
16 |
17 | video_size_view = OpenCensus::Stats.create_view(
18 | name: "my.org/views/video_size",
19 | measure: video_size_measure,
20 | aggregation: video_size_distribution,
21 | description: "processed video size over time",
22 | columns: [fontend_key]
23 | )
24 |
25 | stats_recorder = OpenCensus::Stats.recorder
26 | stats_recorder.register_view(video_size_view)
27 |
28 | tag_map = OpenCensus::Tags::TagMap.new(fontend_key => "mobile-ios9.3.5")
29 |
30 | stats_recorder.record(
31 | video_size_measure.measurement(25 * MIB),
32 | tags: tag_map
33 | )
34 |
35 | view_data = stats_recorder.view_data video_size_view.name
36 |
37 | p view_data.data
38 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/formatters.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | require "opencensus/trace/formatters/binary"
17 | require "opencensus/trace/formatters/cloud_trace"
18 | require "opencensus/trace/formatters/trace_context"
19 |
20 | module OpenCensus
21 | module Trace
22 | ##
23 | # The Formatters module contains several implementations of cross-service
24 | # context propagation. Each formatter can serialize and deserialize a
25 | # {OpenCensus::Trace::TraceContextData} instance.
26 | #
27 | module Formatters
28 | end
29 | end
30 | end
31 |
--------------------------------------------------------------------------------
/.rubocop.yml:
--------------------------------------------------------------------------------
1 | AllCops:
2 | Exclude:
3 | - "acceptance/**/*"
4 | - "integration/**/*"
5 | - "opencensus.gemspec"
6 | - "Rakefile"
7 | - "support/**/*"
8 | - "test/**/*"
9 | - "docs/**/*"
10 | - "tmp/**/*"
11 |
12 | Documentation:
13 | Enabled: false
14 |
15 | Layout/EmptyLineAfterGuardClause:
16 | Enabled: false
17 | Layout/EmptyLines:
18 | Enabled: false
19 | Layout/SpaceAroundOperators:
20 | Enabled: false
21 | Metrics/AbcSize:
22 | Max: 25
23 | Metrics/ClassLength:
24 | Enabled: false
25 | Metrics/CyclomaticComplexity:
26 | Max: 10
27 | Metrics/MethodLength:
28 | Max: 20
29 | Metrics/ParameterLists:
30 | Enabled: false
31 | Metrics/PerceivedComplexity:
32 | Max: 10
33 | Style/CaseEquality:
34 | Enabled: false
35 | Style/ClassVars:
36 | Enabled: false
37 | Style/EmptyElse:
38 | Enabled: false
39 | Style/GuardClause:
40 | Enabled: false
41 | Style/MethodDefParentheses:
42 | EnforcedStyle: require_no_parentheses
43 | Style/NumericLiterals:
44 | Enabled: false
45 | Style/RescueModifier:
46 | Enabled: false
47 | Style/StringLiterals:
48 | EnforcedStyle: double_quotes
49 | Style/TrivialAccessors:
50 | Enabled: false
51 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/time_event.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | module OpenCensus
17 | module Trace
18 | ##
19 | # A time-stamped annotation or message event in the Span.
20 | #
21 | class TimeEvent
22 | ##
23 | # The time the event occurred.
24 | #
25 | # @return [Time]
26 | #
27 | attr_reader :time
28 |
29 | ##
30 | # Create a TimeEvent object
31 | #
32 | # @private
33 | #
34 | def initialize time: nil
35 | @time = time || ::Time.now.utc
36 | end
37 | end
38 | end
39 | end
40 |
--------------------------------------------------------------------------------
/docs/Gemfile:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 | source "https://rubygems.org"
3 |
4 | # Hello! This is where you manage which Jekyll version is used to run.
5 | # When you want to use a different version, change it below, save the
6 | # file and run `bundle install`. Run Jekyll with `bundle exec`, like so:
7 | #
8 | # bundle exec jekyll serve
9 | #
10 | # This will help ensure the proper Jekyll version is running.
11 | # Happy Jekylling!
12 | gem "jekyll", "~> 3.6.2"
13 |
14 | # This is the default theme for new Jekyll sites. You may change this to anything you like.
15 | # gem "minima", "~> 2.0"
16 | gem "jekyll-theme-minimal", "~> 0.1"
17 | # gem "minimal"
18 |
19 | # If you want to use GitHub Pages, remove the "gem "jekyll"" above and
20 | # uncomment the line below. To upgrade, run `bundle update github-pages`.
21 | # gem "github-pages", group: :jekyll_plugins
22 |
23 | # If you have any plugins, put them here!
24 | group :jekyll_plugins do
25 | gem "jekyll-feed", "~> 0.6"
26 | end
27 |
28 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
29 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
30 |
31 | gem "github-pages", group: :jekyll_plugins
32 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/samplers/always_sample.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | module OpenCensus
17 | module Trace
18 | module Samplers
19 | ##
20 | # The AlwaysSample sampler always returns true.
21 | #
22 | class AlwaysSample
23 | ##
24 | # Implements the sampler contract. Checks to see whether a sample
25 | # should be taken at this time.
26 | #
27 | # @return [boolean] Whether to sample at this time.
28 | #
29 | def call _opts = {}
30 | true
31 | end
32 | end
33 | end
34 | end
35 | end
36 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/samplers/never_sample.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | module OpenCensus
17 | module Trace
18 | module Samplers
19 | ##
20 | # The NeverSample sampler always returns false.
21 | #
22 | class NeverSample
23 | ##
24 | # Implements the sampler contract. Checks to see whether a sample
25 | # should be taken at this time.
26 | #
27 | # @return [boolean] Whether to sample at this time.
28 | #
29 | def call _opts = {}
30 | false
31 | end
32 | end
33 | end
34 | end
35 | end
36 |
--------------------------------------------------------------------------------
/test/trace/integrations/rails51_app_template.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | base_dir = File.absolute_path File.dirname File.dirname File.dirname __dir__
16 | gem "opencensus", path: base_dir
17 |
18 | application "require 'opencensus/trace/integrations/rails'"
19 | application "OpenCensus::Trace.configure.exporter = OpenCensus::Trace::Exporters::Logger.new(::Logger.new(STDERR, ::Logger::INFO))"
20 |
21 | route "root to: 'home#index'"
22 |
23 | file "app/controllers/home_controller.rb", <<-CODE
24 | class HomeController < ApplicationController
25 | def index
26 | render plain: "OK"
27 | end
28 | end
29 | CODE
30 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/exporters.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "opencensus/stats/exporters/logger"
4 |
5 | module OpenCensus
6 | module Stats
7 | ##
8 | # The Exporters module provides integrations for exporting collected stats
9 | # to an external or local service. Exporter classes may be put inside
10 | # this module, but are not required to be located here.
11 | #
12 | # An exporter is an object that must respond to the following method:
13 | #
14 | # def export(views_data)
15 | #
16 | # Where `views_data` is an array of {OpenCensus::Stats::ViewData} objects
17 | # to export.
18 | #
19 | # The method return value is not defined.
20 | #
21 | # The exporter object may interpret the `export` message in whatever way it
22 | # deems appropriate. For example, it may write the data to a log file, it
23 | # may transmit it to a monitoring service, or it may do nothing at all.
24 | # An exporter may also queue the request for later asynchronous processing,
25 | # and indeed this is recommended if the export involves time consuming
26 | # operations such as remote API calls.
27 | #
28 | module Exporters
29 | end
30 | end
31 | end
32 |
--------------------------------------------------------------------------------
/lib/opencensus.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | ##
17 | # OpenCensus is a vendor-agnostic single distribution of libraries to provide
18 | # metrics collection and tracing for your services. See https://opencensus.io/
19 | # for general information on OpenCensus.
20 | #
21 | # The OpenCensus module provides a namespace for the Ruby implementation of
22 | # OpenCensus, including the core libraries for OpenCensus metrics and tracing.
23 | #
24 | module OpenCensus
25 | end
26 |
27 | require "opencensus/common"
28 | require "opencensus/config"
29 | require "opencensus/context"
30 | require "opencensus/stats"
31 | require "opencensus/tags"
32 | require "opencensus/trace"
33 | require "opencensus/version"
34 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/exemplar.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | module OpenCensus
5 | module Stats
6 | ##
7 | # Exemplars are example points that may be used to annotate aggregated
8 | # Distribution values. They are metadata that gives information about a
9 | # particular value added to a Distribution bucket.
10 | #
11 | class Exemplar
12 | # Value of the exemplar point. It determines which bucket the exemplar
13 | # belongs to
14 | # @return [Integer,Float]
15 | attr_reader :value
16 |
17 | # The observation (sampling) time of the above value
18 | # @return [Time]
19 | attr_reader :time
20 |
21 | # Contextual information about the example value
22 | # @return [Hash]
23 | attr_reader :attachments
24 |
25 | # Create instance of the exemplar
26 | # @param [Integer,Float] value
27 | # @param [Time] time
28 | # @param [Hash] attachments. Attachments are key-value
29 | # pairs that describe the context in which the exemplar was recored.
30 | def initialize value:, time:, attachments:
31 | @value = value
32 | @time = time
33 |
34 | raise ArgumentError, "attachments can not be empty" if attachments.nil?
35 |
36 | @attachments = attachments
37 | end
38 | end
39 | end
40 | end
41 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/aggregation/distribution.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | module OpenCensus
5 | module Stats
6 | module Aggregation
7 | # Distribution aggregation type
8 | class Distribution
9 | # Invalid bucket types.
10 | class InvalidBucketsError < StandardError; end
11 |
12 | # @return [Array,Array] Bucket boundries.
13 | attr_reader :buckets
14 |
15 | # @private
16 | # @param [Array,Array,] buckets Buckets boundries
17 | # for distribution
18 | # aggregation.
19 | # @raise [InvalidBucketsError] If any bucket value is nil.
20 | def initialize buckets
21 | if buckets.nil? || buckets.empty?
22 | raise InvalidBucketsError, "buckets should not be nil or empty"
23 | end
24 |
25 | if buckets.any?(&:nil?)
26 | raise InvalidBucketsError, "buckets value should not be nil"
27 | end
28 |
29 | @buckets = buckets.reject { |v| v < 0 }
30 | end
31 |
32 | # Create new aggregation data container to store distribution values.
33 | # values.
34 | # @return [AggregationData::Distribution]
35 | def create_aggregation_data
36 | AggregationData::Distribution.new @buckets
37 | end
38 | end
39 | end
40 | end
41 | end
42 |
--------------------------------------------------------------------------------
/opencensus.gemspec:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | lib = File.expand_path("../lib", __FILE__)
3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4 | require "opencensus/version"
5 |
6 | Gem::Specification.new do |spec|
7 | spec.name = "opencensus"
8 | spec.version = OpenCensus::VERSION
9 | spec.authors = ["Jeff Ching", "Daniel Azuma"]
10 | spec.email = ["chingor@google.com", "dazuma@google.com"]
11 |
12 | spec.summary = "A stats collection and distributed tracing framework"
13 | spec.description = "A stats collection and distributed tracing framework"
14 | spec.homepage = "https://github.com/census-instrumentation/opencensus-ruby"
15 | spec.license = "Apache-2.0"
16 |
17 | spec.files = ::Dir.glob("lib/**/*.rb") +
18 | ::Dir.glob("*.md") +
19 | ["AUTHORS", "LICENSE", ".yardopts"]
20 | spec.require_paths = ["lib"]
21 | spec.required_ruby_version = ">= 2.2.0"
22 |
23 | spec.add_development_dependency "bundler", ">= 1.17"
24 | spec.add_development_dependency "rake", "~> 12.0"
25 | spec.add_development_dependency "minitest", "~> 5.0"
26 | spec.add_development_dependency "minitest-focus", "~> 1.1"
27 | spec.add_development_dependency "faraday", "~> 0.13"
28 | spec.add_development_dependency "rails", "~> 5.1.4"
29 | spec.add_development_dependency "rubocop", "~> 0.59.2"
30 | spec.add_development_dependency "yard", "~> 0.9"
31 | spec.add_development_dependency "yard-doctest", "~> 0.1.6"
32 | end
33 |
--------------------------------------------------------------------------------
/docs/_config.yml:
--------------------------------------------------------------------------------
1 | # Welcome to Jekyll!
2 | #
3 | # This config file is meant for settings that affect your whole blog, values
4 | # which you are expected to set up once and rarely edit after that. If you find
5 | # yourself editing this file very often, consider using Jekyll's data files
6 | # feature for the data you need to update frequently.
7 | #
8 | # For technical reasons, this file is *NOT* reloaded automatically when you use
9 | # 'bundle exec jekyll serve'. If you change this file, please restart the server process.
10 |
11 | # Site settings
12 | # These are used to personalize your new site. If you look in the HTML files,
13 | # you will see them accessed via {{ site.title }}, {{ site.email }}, and so on.
14 | # You can create any custom variable you would like, and they will be accessible
15 | # in the templates via {{ site.myvariable }}.
16 | title: OpenCensus for Ruby
17 | email: your-email@example.com
18 | description: A stats collection and distributed tracing framework
19 | baseurl: "/opencensus-ruby" # the subpath of your site, e.g. /blog
20 | url: "http://opencensus.io" # the base hostname & protocol for your site, e.g. http://example.com
21 | github_username: census-instrumentation
22 |
23 | # Build settings
24 | markdown: kramdown
25 | theme: jekyll-theme-minimal
26 | plugins:
27 | - jekyll-feed
28 |
29 | # Exclude from processing.
30 | # The following items will not be processed, by default. Create a custom list
31 | # to override the default setting.
32 | # exclude:
33 | # - Gemfile
34 | # - Gemfile.lock
35 | # - node_modules
36 | # - vendor/bundle/
37 | # - vendor/cache/
38 | # - vendor/gems/
39 | # - vendor/ruby/
40 |
--------------------------------------------------------------------------------
/test/trace/integrations/rails_test.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | require "test_helper"
16 |
17 | require "opencensus/trace/integrations/rails"
18 |
19 | describe OpenCensus::Trace::Integrations::Rails do
20 | describe "#setup_notifications" do
21 | let(:railtie) { OpenCensus::Trace::Integrations::Rails.instance }
22 | after {
23 | ActiveSupport::Notifications.notifier = ActiveSupport::Notifications::Fanout.new
24 | OpenCensus::Trace.unset_span_context
25 | }
26 |
27 | it "creates spans for sql notifications" do
28 | railtie.setup_notifications
29 | OpenCensus::Trace.start_request_trace
30 | ActiveSupport::Notifications.instrument("sql.active_record", query: "hello") do
31 | end
32 | spans = OpenCensus::Trace.span_context.build_contained_spans
33 | spans.size.must_equal 1
34 | span = spans.first
35 | span.name.value.must_equal "sql.active_record"
36 | span.attributes.size.must_equal 1
37 | span.attributes["rails/query"].value.must_equal "hello"
38 | end
39 | end
40 | end
41 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to become a contributor and submit your own code
2 |
3 | ## Contributor License Agreements
4 |
5 | We'd love to accept your patches! Before we can take them, we
6 | have to jump a couple of legal hurdles.
7 |
8 | Please fill out either the individual or corporate Contributor License Agreement
9 | (CLA).
10 |
11 | * If you are an individual writing original source code and you're sure you
12 | own the intellectual property, then you'll need to sign an [individual CLA]
13 | (https://developers.google.com/open-source/cla/individual).
14 | * If you work for a company that wants to allow you to contribute your work,
15 | then you'll need to sign a [corporate CLA]
16 | (https://developers.google.com/open-source/cla/corporate).
17 |
18 | Follow either of the two links above to access the appropriate CLA and
19 | instructions for how to sign and return it. Once we receive it, we'll be able to
20 | accept your pull requests.
21 |
22 | ## Contributing A Patch
23 |
24 | 1. Submit an issue describing your proposed change to the repo in question.
25 | 1. The repo owner will respond to your issue promptly.
26 | 1. If your proposed change is accepted, and you haven't already done so, sign a
27 | Contributor License Agreement (see details above).
28 | 1. Fork the desired repo, develop and test your code changes.
29 | 1. Ensure that your code adheres to the existing style in the sample to which
30 | you are contributing. Refer to the
31 | [Google Cloud Platform Samples Style Guide]
32 | (https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the
33 | recommended coding standards for this organization.
34 | 1. Submit a pull request.
35 |
--------------------------------------------------------------------------------
/test/trace/exporters/multi_test.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | require "test_helper"
16 |
17 | describe OpenCensus::Trace::Exporters::Multi do
18 | describe "export" do
19 | let(:spans) { ["span1", "span2"] }
20 |
21 | it "should delegate to exporters" do
22 | mock1 = Minitest::Mock.new
23 | mock1.expect :export, nil, [spans]
24 | mock2 = Minitest::Mock.new
25 | mock2.expect :export, nil, [spans]
26 |
27 | exporter = OpenCensus::Trace::Exporters::Multi.new mock1, mock2
28 | exporter.export spans
29 |
30 | mock1.verify
31 | mock2.verify
32 | end
33 |
34 | it "should allow empty" do
35 | exporter = OpenCensus::Trace::Exporters::Multi.new
36 | exporter.export spans
37 | end
38 | end
39 |
40 | describe "array management" do
41 | let(:exporter1) { "exporter1" }
42 | let(:exporter2) { "exporter2" }
43 |
44 | it "allows adding to the multi and retrieving by index" do
45 | exporter = OpenCensus::Trace::Exporters::Multi.new
46 | exporter << exporter1
47 | exporter.push exporter2
48 | exporter[0].must_equal exporter1
49 | exporter[1].must_equal exporter2
50 | end
51 | end
52 | end
53 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/view.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | module OpenCensus
5 | module Stats
6 | # View
7 | #
8 | # A View specifies an aggregation and a set of tag keys.
9 | # The aggregation will be broken down by the unique set of matching tag
10 | # values for each measure.
11 | class View
12 | # @return [String] Name of the view
13 | attr_reader :name
14 |
15 | # @return [Measure] Associated measure definition instance.
16 | attr_reader :measure
17 |
18 | # @return [Aggregation] Associated aggregation definition instance.
19 | attr_reader :aggregation
20 |
21 | # Columns (a.k.a Tag Keys) to match with the
22 | # associated Measure. Measure will be recorded in a "greedy" way.
23 | # That is, every view aggregates every measure.
24 | # This is similar to doing a GROUPBY on view columns. Columns must be
25 | # unique.
26 | # @return [Array]
27 | attr_reader :columns
28 |
29 | # @return [String] Detailed description
30 | attr_reader :description
31 |
32 | # @return [Time] View creation time.
33 | attr_reader :time
34 |
35 | # Create instance of the view
36 | #
37 | # @param [String] name
38 | # @param [Measure] measure
39 | # @param [Aggregation] aggregation
40 | # @param [Array] columns
41 | # @param [String] description
42 | def initialize \
43 | name:,
44 | measure:,
45 | aggregation:,
46 | columns:,
47 | description: nil
48 | @name = name
49 | @measure = measure
50 | @aggregation = aggregation
51 | @columns = columns
52 | @description = description
53 | @time = Time.now.utc
54 | end
55 | end
56 | end
57 | end
58 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/view_data.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | module OpenCensus
5 | module Stats
6 | # ViewData is a container to store stats.
7 | class ViewData
8 | # @return [View]
9 | attr_reader :view
10 |
11 | # @return [Time, nil]
12 | attr_reader :start_time
13 |
14 | # @return [Time, nil]
15 | attr_reader :end_time
16 |
17 | # @return [Hash>,AggregationData] Recorded stats data
18 | # against view columns.
19 | attr_reader :data
20 |
21 | # @private
22 | # Create instance of view
23 | #
24 | # @param [View] view
25 | # @param [Time] start_time
26 | # @param [Time] end_time
27 | def initialize view, start_time: nil, end_time: nil
28 | @view = view
29 | @start_time = start_time
30 | @end_time = end_time
31 | @data = {}
32 | end
33 |
34 | # Set start time.
35 | def start
36 | @start_time = Time.now.utc
37 | end
38 |
39 | # Set stop time.
40 | def stop
41 | @end_time = Time.now.utc
42 | end
43 |
44 | # Record a measurement.
45 | #
46 | # @param [Measurement] measurement
47 | # @param [Hash] attachments
48 | def record measurement, attachments: nil
49 | tag_values = @view.columns.map { |column| measurement.tags[column] }
50 |
51 | unless @data.key? tag_values
52 | @data[tag_values] = @view.aggregation.create_aggregation_data
53 | end
54 |
55 | @data[tag_values].add(
56 | measurement.value,
57 | measurement.time,
58 | attachments: attachments
59 | )
60 | end
61 |
62 | # Clear recorded ata
63 | def clear
64 | data.clear
65 | end
66 | end
67 | end
68 | end
69 |
--------------------------------------------------------------------------------
/test/stats/measure_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Stats::Measurement do
4 | describe "create" do
5 | it "int64 type measure" do
6 | measure = OpenCensus::Stats::Measure.new(
7 | name: "latency",
8 | unit: "ms",
9 | type: OpenCensus::Stats::Measure::INT64_TYPE,
10 | description: "latency desc"
11 | )
12 |
13 | measure.name.must_equal "latency"
14 | measure.unit.must_equal "ms"
15 | measure.type.must_equal OpenCensus::Stats::Measure::INT64_TYPE
16 | measure.description.must_equal "latency desc"
17 | measure.int64?.must_equal true
18 | measure.double?.must_equal false
19 | end
20 |
21 | it "double type measure" do
22 | measure = OpenCensus::Stats::Measure.new(
23 | name: "storage",
24 | unit: "kb",
25 | type: OpenCensus::Stats::Measure::DOUBLE_TYPE,
26 | description: "storage desc"
27 | )
28 |
29 | measure.name.must_equal "storage"
30 | measure.unit.must_equal "kb"
31 | measure.type.must_equal OpenCensus::Stats::Measure::DOUBLE_TYPE
32 | measure.description.must_equal "storage desc"
33 | measure.double?.must_equal true
34 | measure.int64?.must_equal false
35 | end
36 | end
37 |
38 | it "create measurement instance" do
39 | measure = OpenCensus::Stats::Measure.new(
40 | name: "storage",
41 | unit: "kb",
42 | type: OpenCensus::Stats::Measure::DOUBLE_TYPE,
43 | description: "storage desc"
44 | )
45 | tags = { "key1" => "val1" }
46 | measurement = measure.create_measurement value: 10.10, tags: tags
47 | measurement.value.must_equal 10.10
48 | measurement.measure.must_equal measure
49 | measurement.tags.must_be_kind_of OpenCensus::Tags::TagMap
50 | measurement.tags.to_h.must_equal tags
51 | end
52 | end
53 |
--------------------------------------------------------------------------------
/lib/opencensus/config.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | require "opencensus/common/config"
17 |
18 | module OpenCensus
19 | # The OpenCensus overall configuration.
20 | @config = Common::Config.new
21 |
22 | class << self
23 | ##
24 | # Configure OpenCensus. Most configuration parameters are defined in
25 | # subconfigurations that live under this main configuration. See, for
26 | # example, {OpenCensus::Trace.configure}.
27 | #
28 | # If the OpenCensus Railtie is installed in a Rails application, the
29 | # toplevel configuration object is also exposed as `config.opencensus`.
30 | #
31 | # Generally, you should configure this once at process initialization,
32 | # but it can be modified at any time.
33 | #
34 | # Example:
35 | #
36 | # OpenCensus.configure do |config|
37 | # config.trace.default_sampler =
38 | # OpenCensus::Trace::Samplers::RateLimiting.new
39 | # config.trace.default_max_attributes = 16
40 | # end
41 | #
42 | def configure
43 | if block_given?
44 | yield @config
45 | else
46 | @config
47 | end
48 | end
49 |
50 | ##
51 | # Get the current configuration.
52 | # @private
53 | #
54 | attr_reader :config
55 | end
56 | end
57 |
--------------------------------------------------------------------------------
/test/trace/formatters/cloud_trace_test.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | require "test_helper"
16 |
17 | describe OpenCensus::Trace::Formatters::CloudTrace do
18 | let(:formatter) { OpenCensus::Trace::Formatters::CloudTrace.new }
19 |
20 | describe "deserialize" do
21 | it "should return nil on invalid format" do
22 | data = formatter.deserialize "badvalue"
23 | data.must_be_nil
24 | end
25 |
26 | it "should parse a valid format" do
27 | data = formatter.deserialize "123456789012345678901234567890ab/1234;o=1"
28 | data.wont_be_nil
29 | data.trace_id.must_equal "123456789012345678901234567890ab"
30 | data.span_id.must_equal "00000000000004d2"
31 | data.trace_options.must_equal 1
32 | end
33 | end
34 |
35 | describe "serialize" do
36 | let(:trace_data) do
37 | OpenCensus::Trace::SpanContext::TraceData.new(
38 | "123456789012345678901234567890ab",
39 | {}
40 | )
41 | end
42 | let(:span_context) do
43 | OpenCensus::Trace::SpanContext.new trace_data, nil, "00000000000004d2", 1, nil
44 | end
45 |
46 | it "should serialize a SpanContext object" do
47 | header = formatter.serialize span_context
48 | header.must_equal "123456789012345678901234567890ab/1234;o=1"
49 | end
50 | end
51 | end
52 |
--------------------------------------------------------------------------------
/test/trace/formatters/binary_test.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | require "test_helper"
16 |
17 | describe OpenCensus::Trace::Formatters::Binary do
18 | let(:formatter) { OpenCensus::Trace::Formatters::Binary.new }
19 |
20 | describe "deserialize" do
21 | it "should return nil on invalid format" do
22 | data = formatter.deserialize "badvalue"
23 | data.must_be_nil
24 | end
25 |
26 | it "should parse a valid format" do
27 | data = formatter.deserialize ["0000123456789012345678901234567890ab0100000000000004d20201"].pack("H*")
28 | data.wont_be_nil
29 | data.trace_id.must_equal "123456789012345678901234567890ab"
30 | data.span_id.must_equal "00000000000004d2"
31 | data.trace_options.must_equal 1
32 | end
33 | end
34 |
35 | describe "serialize" do
36 | let(:trace_data) do
37 | OpenCensus::Trace::SpanContext::TraceData.new(
38 | "123456789012345678901234567890ab",
39 | {}
40 | )
41 | end
42 | let(:span_context) do
43 | OpenCensus::Trace::SpanContext.new trace_data, nil, "00000000000004d2", 1, nil
44 | end
45 |
46 | it "should serialize a SpanContext object" do
47 | header = formatter.serialize span_context
48 | header.must_equal ["0000123456789012345678901234567890ab0100000000000004d20201"].pack("H*")
49 | end
50 | end
51 | end
52 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/exporters.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | require "opencensus/trace/exporters/logger"
17 | require "opencensus/trace/exporters/multi"
18 |
19 | module OpenCensus
20 | module Trace
21 | ##
22 | # The Exporters module provides integrations for exporting collected trace
23 | # spans to an external or local service. Exporter classes may be put inside
24 | # this module, but are not required to be located here.
25 | #
26 | # An exporter is an object that must respond to the following method:
27 | #
28 | # def export(spans)
29 | #
30 | # Where `spans` is an array of {OpenCensus::Trace::Span} objects to export.
31 | # The method _must_ tolerate any number of spans in the `spans` array,
32 | # including an empty array.
33 | #
34 | # The method return value is not defined.
35 | #
36 | # The exporter object may interpret the `export` message in whatever way it
37 | # deems appropriate. For example, it may write the data to a log file, it
38 | # may transmit it to a monitoring service, or it may do nothing at all.
39 | # An exporter may also queue the request for later asynchronous processing,
40 | # and indeed this is recommended if the export involves time consuming
41 | # operations such as remote API calls.
42 | #
43 | module Exporters
44 | end
45 | end
46 | end
47 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/measure_registry.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | require "singleton"
5 | require "opencensus/stats/measure"
6 |
7 | module OpenCensus
8 | module Stats
9 | # #MeasureRegistry
10 | #
11 | # Measure registry is a collection of uniq measures.
12 | #
13 | class MeasureRegistry
14 | include Singleton
15 |
16 | # @return [Hash]
17 | attr_reader :measures
18 |
19 | # @private
20 | def initialize
21 | @measures = {}
22 | end
23 |
24 | class << self
25 | # Register measure.
26 | #
27 | # @param [String] name Name of measure
28 | # @param [String] unit Unit name of measure
29 | # @param [String] type Date type unit of measure. integer or float.
30 | # @param [String] description Description of measure
31 | # @return [Measure, nil]
32 | #
33 | def register name:, unit:, type:, description: nil
34 | return if instance.measures.key? name
35 |
36 | measure = Measure.new(
37 | name: name,
38 | unit: unit,
39 | type: type,
40 | description: description
41 | )
42 |
43 | instance.measures[name] = measure
44 | end
45 |
46 | # Un register measure
47 | #
48 | # @param [String] name Name of the registered view
49 | def unregister name
50 | instance.measures.delete name
51 | end
52 |
53 | # Clear measures registry
54 | def clear
55 | instance.measures.clear
56 | end
57 |
58 | # Get registered measure
59 | # @return [Measure]
60 | def get name
61 | instance.measures[name]
62 | end
63 |
64 | # List of registered measures
65 | # @return [Array]
66 | def measures
67 | instance.measures.values
68 | end
69 | end
70 | end
71 | end
72 | end
73 |
--------------------------------------------------------------------------------
/lib/opencensus/tags.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | # Copyright 2017 OpenCensus Authors
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License");
6 | # you may not use this file except in compliance with the License.
7 | # You may obtain a copy of the License at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # Unless required by applicable law or agreed to in writing, software
12 | # distributed under the License is distributed on an "AS IS" BASIS,
13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | # See the License for the specific language governing permissions and
15 | # limitations under the License.
16 |
17 |
18 | require "opencensus/tags/config"
19 | require "opencensus/tags/tag_map"
20 | require "opencensus/tags/formatters"
21 |
22 | module OpenCensus
23 | ##
24 | # The Tags module contains support for OpenCensus tags. Tags are key-value
25 | # pairs. Tags provide additional cardinality to the OpenCensus instrumentation
26 | # data.
27 | #
28 | module Tags
29 | ##
30 | # Internal key for storing the current TagMap in the thread local
31 | # Context
32 | #
33 | # @private
34 | #
35 | TAG_MAP_CONTEXT_KEY = :__tag_map_context__
36 |
37 | class << self
38 | ##
39 | # Sets the current thread-local TagMap, which used in Stats data
40 | # recording.
41 | #
42 | # @param [TagMap] context
43 | #
44 | def tag_map_context= context
45 | OpenCensus::Context.set TAG_MAP_CONTEXT_KEY, context
46 | end
47 |
48 | # Unsets the current thread-local TagMap context
49 | #
50 | def unset_tag_map_context
51 | OpenCensus::Context.unset TAG_MAP_CONTEXT_KEY
52 | end
53 |
54 | # Returns the current thread-local TagMap object.
55 | #
56 | # @return [TagMap, nil]
57 | #
58 | def tag_map_context
59 | OpenCensus::Context.get TAG_MAP_CONTEXT_KEY
60 | end
61 | end
62 | end
63 | end
64 |
--------------------------------------------------------------------------------
/test/stats/exporters/logger_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Stats::Exporters::Logger do
4 | before{
5 | OpenCensus::Tags.unset_tag_map_context
6 | }
7 |
8 | let(:logger) {
9 | logger = ::Logger.new STDOUT
10 | logger.level = ::Logger::INFO
11 | logger.formatter = -> (_, _, _, msg) { msg }
12 | logger
13 | }
14 | let(:measure){
15 | OpenCensus::Stats::Measure.new(
16 | name: "latency",
17 | unit: "ms",
18 | type: OpenCensus::Stats::Measure::INT64_TYPE,
19 | description: "latency desc"
20 | )
21 | }
22 | let(:aggregation){ OpenCensus::Stats::Aggregation::Sum.new }
23 | let(:tag_keys) { ["frontend"]}
24 | let(:view) {
25 | OpenCensus::Stats::View.new(
26 | name: "test.view",
27 | measure: measure,
28 | aggregation: aggregation,
29 | description: "Test view",
30 | columns: tag_keys
31 | )
32 | }
33 | let(:tag_map) {
34 | OpenCensus::Tags::TagMap.new(tag_keys.first => "mobile-ios9.3.5")
35 | }
36 | let(:tags){
37 | { tag_keys.first => "mobile-ios9.3.5" }
38 | }
39 | let(:view_data){
40 | recorder = OpenCensus::Stats::Recorder.new
41 | recorder.register_view view
42 | recorder.record measure.create_measurement(value: 10, tags: tags)
43 | view_data = recorder.view_data view.name
44 | [view_data]
45 | }
46 |
47 | describe "export" do
48 | it "should emit data for a covered log level" do
49 | exporter = OpenCensus::Stats::Exporters::Logger.new logger, level: ::Logger::INFO
50 | out, _err = capture_subprocess_io do
51 | exporter.export view_data
52 | end
53 |
54 | out.wont_be_empty
55 | end
56 |
57 | it "should not emit data for a low log level" do
58 | exporter = OpenCensus::Stats::Exporters::Logger.new logger, level: ::Logger::DEBUG
59 | out, _err = capture_subprocess_io do
60 | exporter.export view_data
61 | end
62 |
63 | out.must_be_empty
64 | end
65 | end
66 | end
67 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/annotation.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | require "opencensus/trace/time_event"
17 |
18 | module OpenCensus
19 | module Trace
20 | ##
21 | # A text annotation with a set of attributes.
22 | #
23 | class Annotation < TimeEvent
24 | ##
25 | # A user-supplied message describing the event.
26 | #
27 | # @return [TruncatableString]
28 | #
29 | attr_reader :description
30 |
31 | ##
32 | # A set of attributes on the annotation.
33 | #
34 | # @return [Hash]
35 | #
36 | attr_reader :attributes
37 |
38 | ##
39 | # The number of attributes that were discarded. Attributes can be
40 | # discarded because their keys are too long or because there are too
41 | # many attributes. If this value is 0, then no attributes were dropped.
42 | #
43 | # @return [Integer]
44 | #
45 | attr_reader :dropped_attributes_count
46 |
47 | ##
48 | # Create an Annotation object.
49 | #
50 | # @private
51 | #
52 | def initialize description, attributes: {}, dropped_attributes_count: 0,
53 | time: nil
54 | super time: time
55 | @description = description
56 | @attributes = attributes
57 | @dropped_attributes_count = dropped_attributes_count
58 | end
59 | end
60 | end
61 | end
62 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/exporters/multi.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2018 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | require "delegate"
17 |
18 | module OpenCensus
19 | module Trace
20 | module Exporters
21 | ##
22 | # The Multi exporter multiplexes captured spans to a set of delegate
23 | # exporters. It is useful if you need to export to more than one
24 | # destination. You may also use it as a "null" exporter by providing
25 | # no delegates.
26 | #
27 | # Multi delegates to an array of the exporter objects. You can manage
28 | # the list of exporters using any method of Array. For example:
29 | #
30 | # multi = OpenCensus::Trace::Exporters::Multi.new
31 | # multi.export(spans) # Does nothing
32 | # multi << OpenCensus::Trace::Exporters::Logger.new
33 | # multi.export(spans) # Exports to the logger
34 | #
35 | class Multi < SimpleDelegator
36 | ##
37 | # Create a new Multi exporter
38 | #
39 | # @param [Array<#export>] delegates An array of exporters
40 | #
41 | def initialize *delegates
42 | super(delegates.flatten)
43 | end
44 |
45 | ##
46 | # Pass the captured spans to the delegates.
47 | #
48 | # @param [Array] spans The captured spans.
49 | #
50 | def export spans
51 | each { |delegate| delegate.export spans }
52 | nil
53 | end
54 | end
55 | end
56 | end
57 | end
58 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/exporters/multi.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2018 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | require "delegate"
17 |
18 | module OpenCensus
19 | module Stats
20 | module Exporters
21 | ##
22 | # The Multi exporter multiplexes captured stats to a set of delegate
23 | # exporters. It is useful if you need to export to more than one
24 | # destination. You may also use it as a "null" exporter by providing
25 | # no delegates.
26 | #
27 | # Multi delegates to an array of the exporter objects. You can manage
28 | # the list of exporters using any method of Array. For example:
29 | #
30 | # multi = OpenCensus::Stats::Exporters::Multi.new
31 | # multi.export(views_data) # Does nothing
32 | # multi << OpenCensus::Stats::Exporters::Logger.new
33 | # multi.export(views_data) # Exports to the logger
34 | #
35 | class Multi < SimpleDelegator
36 | ##
37 | # Create a new Multi exporter
38 | #
39 | # @param [Array<#export>] delegates An array of exporters
40 | #
41 | def initialize *delegates
42 | super(delegates.flatten)
43 | end
44 |
45 | ##
46 | # Pass the captured stats view data to the delegates.
47 | #
48 | # @param [Array] views_data The captured stats.
49 | #
50 | def export views_data
51 | each { |delegate| delegate.export views_data }
52 | nil
53 | end
54 | end
55 | end
56 | end
57 | end
58 |
--------------------------------------------------------------------------------
/test/trace/formatters/trace_context_test.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | require "test_helper"
16 |
17 | describe OpenCensus::Trace::Formatters::TraceContext do
18 | let(:formatter) { OpenCensus::Trace::Formatters::TraceContext.new }
19 |
20 | describe "deserialize" do
21 | it "should return nil on invalid format" do
22 | data = formatter.deserialize "badvalue"
23 | data.must_be_nil
24 | end
25 |
26 | it "should return nil on unsupported version" do
27 | data = formatter.deserialize "ff-0123456789abcdef0123456789abcdef-0123456789abcdef-01"
28 | data.must_be_nil
29 | end
30 |
31 | it "should parse a valid format" do
32 | data = formatter.deserialize "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"
33 | data.wont_be_nil
34 | data.trace_id.must_equal "0123456789abcdef0123456789abcdef"
35 | data.span_id.must_equal "0123456789abcdef"
36 | data.trace_options.must_equal 1
37 | end
38 | end
39 |
40 | describe "serialize" do
41 | let(:trace_data) do
42 | OpenCensus::Trace::SpanContext::TraceData.new(
43 | "0123456789abcdef0123456789abcdef",
44 | {}
45 | )
46 | end
47 | let(:span_context) do
48 | OpenCensus::Trace::SpanContext.new trace_data, nil, "0123456789abcdef", 1, nil
49 | end
50 |
51 | it "should serialize a SpanContext object" do
52 | header = formatter.serialize span_context
53 | header.must_equal "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"
54 | end
55 | end
56 | end
57 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Code of Conduct
2 |
3 | As contributors and maintainers of this project,
4 | and in the interest of fostering an open and welcoming community,
5 | we pledge to respect all people who contribute through reporting issues,
6 | posting feature requests, updating documentation,
7 | submitting pull requests or patches, and other activities.
8 |
9 | We are committed to making participation in this project
10 | a harassment-free experience for everyone,
11 | regardless of level of experience, gender, gender identity and expression,
12 | sexual orientation, disability, personal appearance,
13 | body size, race, ethnicity, age, religion, or nationality.
14 |
15 | Examples of unacceptable behavior by participants include:
16 |
17 | * The use of sexualized language or imagery
18 | * Personal attacks
19 | * Trolling or insulting/derogatory comments
20 | * Public or private harassment
21 | * Publishing other's private information,
22 | such as physical or electronic
23 | addresses, without explicit permission
24 | * Other unethical or unprofessional conduct.
25 |
26 | Project maintainers have the right and responsibility to remove, edit, or reject
27 | comments, commits, code, wiki edits, issues, and other contributions
28 | that are not aligned to this Code of Conduct.
29 | By adopting this Code of Conduct,
30 | project maintainers commit themselves to fairly and consistently
31 | applying these principles to every aspect of managing this project.
32 | Project maintainers who do not follow or enforce the Code of Conduct
33 | may be permanently removed from the project team.
34 |
35 | This code of conduct applies both within project spaces and in public spaces
36 | when an individual is representing the project or its community.
37 |
38 | Instances of abusive, harassing, or otherwise unacceptable behavior
39 | may be reported by opening an issue
40 | or contacting one or more of the project maintainers.
41 |
42 | This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0,
43 | available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/)
44 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/truncatable_string.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | module OpenCensus
17 | module Trace
18 | ##
19 | # A string that might be shortened to a specified length.
20 | #
21 | class TruncatableString
22 | ##
23 | # The shortened string. For example, if the original string was 500 bytes
24 | # long and the limit of the string was 128 bytes, then this value contains
25 | # the first 128 bytes of the 500-byte string. Note that truncation always
26 | # happens on a character boundary, to ensure that a truncated string is
27 | # still valid UTF-8. Because it may contain multi-byte characters, the
28 | # size of the truncated string may be less than the truncation limit.
29 | #
30 | # @return [String]
31 | #
32 | attr_reader :value
33 |
34 | ##
35 | # The number of bytes removed from the original string. If this value is
36 | # 0, then the string was not shortened.
37 | #
38 | # @return [Integer]
39 | #
40 | attr_reader :truncated_byte_count
41 |
42 | ##
43 | # Create an empty TruncatableString object.
44 | #
45 | # @private
46 | #
47 | def initialize value, truncated_byte_count: 0
48 | @value = value
49 | @truncated_byte_count = truncated_byte_count
50 | end
51 |
52 | ##
53 | # Override the default to_s implementation.
54 | #
55 | # @private
56 | #
57 | def to_s
58 | @value
59 | end
60 | end
61 | end
62 | end
63 |
--------------------------------------------------------------------------------
/lib/opencensus/context.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | module OpenCensus
17 | ##
18 | # The Context module provides per-thread storage.
19 | #
20 | module Context
21 | ##
22 | # Thread local storage key under which all OpenCensus context data is
23 | # stored.
24 | #
25 | # @private
26 | #
27 | THREAD_KEY = :__opencensus_context__
28 |
29 | class << self
30 | ##
31 | # Store a value in the context.
32 | #
33 | # @param [String, Symbol] key The name of the context value to store.
34 | # @param [Object] value The value associated with the key.
35 | def set key, value
36 | storage[key] = value
37 | end
38 |
39 | ##
40 | # Return a value from the context. Returns nil if no value is set.
41 | #
42 | # @param [String, Symbol] key The name of the context value to fetch.
43 | # @return [Object, nil] The fetched value.
44 | #
45 | def get key
46 | storage[key]
47 | end
48 |
49 | ##
50 | # Unsets a value from the context.
51 | #
52 | # @param [String, Symbol] key The name of the context value to unset.
53 | # @return [Object, nil] The value of the context value just unset.
54 | #
55 | def unset key
56 | storage.delete key
57 | end
58 |
59 | ##
60 | # Clears all values from the context.
61 | #
62 | def reset!
63 | Thread.current[THREAD_KEY] = {}
64 | end
65 |
66 | private
67 |
68 | def storage
69 | Thread.current[THREAD_KEY] ||= {}
70 | end
71 | end
72 | end
73 | end
74 |
--------------------------------------------------------------------------------
/test/trace/samplers/probability_test.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | require "test_helper"
16 |
17 | describe OpenCensus::Trace::Samplers::Probability do
18 | describe ".call" do
19 | it "should return true if rng < rate" do
20 | rng = TestRandom.new [0.2]
21 | sampler = OpenCensus::Trace::Samplers::Probability.new 0.5, rng: rng
22 | sampler.call.must_equal true
23 | end
24 |
25 | it "should return true if rng == rate" do
26 | rng = TestRandom.new [0.5]
27 | sampler = OpenCensus::Trace::Samplers::Probability.new 0.5, rng: rng
28 | sampler.call.must_equal true
29 | end
30 |
31 | it "should return false if rng < rate" do
32 | rng = TestRandom.new [0.7]
33 | sampler = OpenCensus::Trace::Samplers::Probability.new 0.5, rng: rng
34 | sampler.call.must_equal false
35 | end
36 |
37 | describe "with 1.0 rate" do
38 | let(:sampler) { OpenCensus::Trace::Samplers::Probability.new 1.0 }
39 |
40 | it "should always return true" do
41 | sampler.call.must_equal true
42 | end
43 | end
44 |
45 | describe "with 0.0 rate" do
46 | let(:sampler) { OpenCensus::Trace::Samplers::Probability.new 0.0 }
47 |
48 | it "should return false" do
49 | sampler.call.must_equal false
50 | end
51 |
52 | it "should return true anyway if the span context is sampled" do
53 | trace_context = OpenCensus::Trace::TraceContextData.new "1", "2", 1
54 | span_context = OpenCensus::Trace::SpanContext.create_root \
55 | trace_context: trace_context
56 | sampler.call(span_context: span_context).must_equal true
57 | end
58 | end
59 | end
60 | end
61 |
--------------------------------------------------------------------------------
/test/stats/aggregation/distribution_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Stats::Aggregation::Distribution do
4 | let(:buckets) {
5 | [1,5,10]
6 | }
7 |
8 | describe "create" do
9 | it "create instance with buckets" do
10 | distribution_aggregation =
11 | OpenCensus::Stats::Aggregation::Distribution.new buckets
12 | distribution_aggregation.buckets.must_equal buckets
13 | end
14 |
15 | it "raise error if buckets value nil" do
16 | expect {
17 | OpenCensus::Stats::Aggregation::Distribution.new nil
18 | }.must_raise OpenCensus::Stats::Aggregation::Distribution::InvalidBucketsError
19 | end
20 |
21 | it "raise error if buckets are empty" do
22 | expect {
23 | OpenCensus::Stats::Aggregation::Distribution.new []
24 | }.must_raise OpenCensus::Stats::Aggregation::Distribution::InvalidBucketsError
25 | end
26 |
27 | it "raise error if any bucket value is nil " do
28 | expect {
29 | OpenCensus::Stats::Aggregation::Distribution.new [1, nil]
30 | }.must_raise OpenCensus::Stats::Aggregation::Distribution::InvalidBucketsError
31 | end
32 |
33 | it "reject bucket value if value is less then zero" do
34 | distribution_aggregation =
35 | OpenCensus::Stats::Aggregation::Distribution.new [1, -1, 10, -20]
36 | distribution_aggregation.buckets.must_equal [1, 10]
37 | end
38 | end
39 |
40 | describe "create_aggregation_data" do
41 | it "create distribution aggregation data instance with default values" do
42 | distribution_aggregation =
43 | OpenCensus::Stats::Aggregation::Distribution.new buckets
44 | aggregation_data = distribution_aggregation.create_aggregation_data
45 | aggregation_data.must_be_kind_of OpenCensus::Stats::AggregationData::Distribution
46 | aggregation_data.count.must_equal 0
47 | aggregation_data.sum.must_equal 0
48 | aggregation_data.max.must_equal(-Float::INFINITY)
49 | aggregation_data.min.must_equal Float::INFINITY
50 | aggregation_data.mean.must_equal 0
51 | aggregation_data.sum_of_squared_deviation.must_equal 0
52 | aggregation_data.buckets.must_equal buckets
53 | aggregation_data.bucket_counts.must_equal [0,0,0,0]
54 | end
55 | end
56 | end
57 |
--------------------------------------------------------------------------------
/lib/opencensus/stats/exporters/logger.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 |
4 | require "logger"
5 | require "json"
6 |
7 | module OpenCensus
8 | module Stats
9 | module Exporters
10 | ##
11 | # The Logger exporter exports captured stats view data to a standard
12 | # Ruby Logger interface.
13 | #
14 | class Logger
15 | ##
16 | # Create a new Logger exporter
17 | #
18 | # @param [#log] logger The logger to write to.
19 | # @param [Integer] level The log level. This should be a log level
20 | # defined by the Logger standard library. Default is
21 | # `::Logger::INFO`.
22 | #
23 | def initialize logger, level: ::Logger::INFO
24 | @logger = logger
25 | @level = level
26 | end
27 |
28 | ##
29 | # Export the captured stats to the configured logger.
30 | #
31 | # @param [Array] views_data The captured stats data.
32 | #
33 | def export views_data
34 | stats_data = views_data.map { |vd| format_view_data(vd) }
35 | @logger.log @level, stats_data.to_json
36 | nil
37 | end
38 |
39 | private
40 |
41 | def format_view_data view_data
42 | {
43 | view: format_view(view_data.view),
44 | measure: format_measure(view_data.view.measure),
45 | aggregation: format_aggregation(view_data)
46 | }
47 | end
48 |
49 | def format_view view
50 | {
51 | name: view.name,
52 | columns: view.columns,
53 | description: view.description
54 | }
55 | end
56 |
57 | def format_measure measure
58 | {
59 | name: measure.name,
60 | unit: measure.unit,
61 | type: measure.type,
62 | description: measure.description
63 | }
64 | end
65 |
66 | def format_aggregation view_data
67 | {
68 | type: view_data.view.aggregation.class.name.downcase,
69 | start_time: view_data.start_time,
70 | end_time: view_data.end_time,
71 | data: view_data.data
72 | }
73 | end
74 | end
75 | end
76 | end
77 | end
78 |
--------------------------------------------------------------------------------
/examples/hello-world/hello.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2018 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | # This is a simple Sinatra application demonstrating how to record traces
17 | # using OpenCensus.
18 | #
19 | # It uses the OpenCensus Rack middleware to trace all incoming requests. It
20 | # also demonstrates how to use the Faraday middleware to trace outgoing HTTP
21 | # requests, as well as how to instrument your code to capture custom spans.
22 | #
23 | # By default, the resulting trace data is logged in JSON format. You can also
24 | # configure OpenCensus to report traces to a backend such as Stackdriver or
25 | # Zipkin using an exporter plugin library.
26 |
27 | require "sinatra"
28 |
29 | # Install the Rack middleware to trace incoming requests.
30 | require "opencensus/trace/integrations/rack_middleware"
31 | use OpenCensus::Trace::Integrations::RackMiddleware
32 |
33 | # Access the Faraday middleware which will be used to trace outgoing HTTP
34 | # requests.
35 | require "opencensus/trace/integrations/faraday_middleware"
36 |
37 | # Each request will be traced automatically by the middleware.
38 | get "/" do
39 | "Hello world!"
40 | end
41 |
42 | # Traces for this request will also include sub-spans as indicated below.
43 | get "/lengthy" do
44 | # Configure this Faraday connection with a middleware to trace outgoing
45 | # requests.
46 | conn = Faraday.new(url: "http://www.google.com") do |c|
47 | c.use OpenCensus::Trace::Integrations::FaradayMiddleware
48 | c.adapter Faraday.default_adapter
49 | end
50 | conn.get "/"
51 |
52 | # You may instrument your code to create custom spans for long-running
53 | # operations.
54 | OpenCensus::Trace.in_span "long task" do
55 | sleep rand
56 | end
57 |
58 | "Done!"
59 | end
60 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/formatters/binary.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | module OpenCensus
17 | module Trace
18 | module Formatters
19 | ##
20 | # This formatter serializes and deserializes span context according to
21 | # the OpenCensus' BinaryEncoding specification. See
22 | # [documentation](https://github.com/census-instrumentation/opencensus-specs/blob/master/encodings/BinaryEncoding.md).
23 | #
24 | class Binary
25 | ##
26 | # Internal format used to (un)pack binary data
27 | #
28 | # @private
29 | #
30 | BINARY_FORMAT = "CCH32CH16CC".freeze
31 |
32 | ##
33 | # Deserialize a trace context header into a TraceContext object.
34 | #
35 | # @param [String] binary
36 | # @return [TraceContextData, nil]
37 | #
38 | def deserialize binary
39 | data = binary.unpack(BINARY_FORMAT)
40 | if data[0].zero? && data[1].zero? && data[3] == 1 && data[5] == 2
41 | TraceContextData.new data[2], data[4], data[6]
42 | else
43 | nil
44 | end
45 | end
46 |
47 | ##
48 | # Serialize a TraceContextData object.
49 | #
50 | # @param [TraceContextData] trace_context
51 | # @return [String]
52 | #
53 | def serialize trace_context
54 | [
55 | 0, # version
56 | 0, # field 0
57 | trace_context.trace_id,
58 | 1, # field 1
59 | trace_context.span_id,
60 | 2, # field 2
61 | trace_context.trace_options
62 | ].pack(BINARY_FORMAT)
63 | end
64 | end
65 | end
66 | end
67 | end
68 |
--------------------------------------------------------------------------------
/test/tags/formatters/binary_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | describe OpenCensus::Tags::Formatters::Binary do
4 | let(:formatter) { OpenCensus::Tags::Formatters::Binary.new }
5 |
6 | describe "serialize" do
7 | it "return serialize tag map binary data" do
8 | tag_map = OpenCensus::Tags::TagMap.new({
9 | "key1" => "val1",
10 | "key2" => "val2",
11 | "key3" => "val3",
12 | "key4" => "val4",
13 | })
14 |
15 | binary = formatter.serialize(tag_map)
16 | expected_binary = "\x00\x00\x04key1\x04val1\x00\x04key2\x04val2\x00\x04key3\x04val3\x00\x04key4\x04val4"
17 | binary.must_equal expected_binary
18 | end
19 |
20 | it "return nil if tag map serialize data size more then 8192 bytes" do
21 | tag_map = OpenCensus::Tags::TagMap.new
22 |
23 | 500.times do |i|
24 | tag_map["key#{i}"] = "value#{i}"
25 | end
26 |
27 | binary = formatter.serialize(tag_map)
28 | binary.must_be_nil
29 | end
30 | end
31 |
32 | describe "deserialize" do
33 | it "deserialize binary data" do
34 | binary = "\x00\x00\x04key1\x04val1\x00\x04key2\x04val2\x00\x04key3\x04val3\x00\x04key4\x04val4"
35 |
36 | tag_map = formatter.deserialize binary
37 | tag_map.length.must_equal 4
38 |
39 | expected_tag_map_values = {
40 | "key1" => "val1",
41 | "key2" => "val2",
42 | "key3" => "val3",
43 | "key4" => "val4",
44 | }
45 | tag_map.to_h.must_equal expected_tag_map_values
46 | end
47 |
48 | it "returns empty tag map for empty string" do
49 | tag_map = formatter.deserialize ""
50 | tag_map.length.must_equal 0
51 | end
52 |
53 | it "returns empty tag map for nil" do
54 | tag_map = formatter.deserialize nil
55 | tag_map.length.must_equal 0
56 | end
57 |
58 | it "raise an error for invalid verion id" do
59 | binary = "\x01\x00\x04key1\x04val1"
60 |
61 | error = expect {
62 | formatter.deserialize binary
63 | }.must_raise OpenCensus::Tags::Formatters::Binary::BinaryFormatterError
64 | error.message.must_match(/invalid version id/i)
65 | end
66 |
67 | it "stop parsing subsequent tags if found invalid field tag id" do
68 | binary = "\x00\x00\x04key1\x04val1\x01\x04key2\x04val2\x00\x04key3\x04val3"
69 |
70 | tag_map = formatter.deserialize binary
71 | tag_map.to_h.must_equal({ "key1" => "val1" })
72 | end
73 | end
74 | end
75 |
--------------------------------------------------------------------------------
/lib/opencensus/trace/samplers.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | require "opencensus/trace/samplers/always_sample"
17 | require "opencensus/trace/samplers/never_sample"
18 | require "opencensus/trace/samplers/probability"
19 | require "opencensus/trace/samplers/rate_limiting"
20 |
21 | module OpenCensus
22 | module Trace
23 | ##
24 | # A sampler determines whether a given request's latency trace should
25 | # actually be reported. It is usually not necessary to trace every
26 | # request, especially for an application serving heavy traffic. You may
27 | # use a sampler to decide, for a given request, whether to report its
28 | # trace.
29 | #
30 | # The OpenCensus specification defines four samplers:
31 | # {OpenCensus::Trace::Samplers::AlwaysSample},
32 | # {OpenCensus::Trace::Samplers::NeverSample},
33 | # {OpenCensus::Trace::Samplers::Probability}, and
34 | # {OpenCensus::Trace::Samplers::RateLimiting}.
35 | #
36 | # A sampler is a `Proc` that takes a hash of environment information and
37 | # returns a boolean indicating whether or not to sample the current
38 | # request. Alternately, it could be an object that duck-types the `Proc`
39 | # interface by implementing the `call` method. The hash passed to `call`
40 | # may contain the following keys, all of which are optional. Samplers must
41 | # adjust their behavior to account for the availability or absence of any
42 | # environment information:
43 | #
44 | # * `span_context` The {OpenCensus::Trace::SpanContext} that created the
45 | # span being sampled.
46 | # * `rack_env` The hash of Rack environment information
47 | #
48 | # Applications may set a default sampler in the config. In addition, the
49 | # sampler may be overridden whenever a span is created.
50 | #
51 | module Samplers
52 | end
53 | end
54 | end
55 |
--------------------------------------------------------------------------------
/test/trace/samplers/rate_limiting_test.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | require "test_helper"
16 |
17 | describe OpenCensus::Trace::Samplers::RateLimiting do
18 | let(:start_time) { ::Time.at 10000000.0 }
19 | let(:time_200ms) { ::Time.at 10000000.2 }
20 | let(:time_400ms) { ::Time.at 10000000.4 }
21 | let(:env) { {} }
22 |
23 | describe ".call" do
24 | it "returns true if rng < elapsed" do
25 | rng = TestRandom.new [0.1]
26 | time_class = TestTimeClass.new [start_time, time_200ms]
27 | sampler = OpenCensus::Trace::Samplers::RateLimiting.new \
28 | 1.0, rng: rng, time_class: time_class
29 | sampler.call.must_equal true
30 | end
31 |
32 | it "returns false if rng > elapsed" do
33 | rng = TestRandom.new [0.3]
34 | time_class = TestTimeClass.new [start_time, time_200ms]
35 | sampler = OpenCensus::Trace::Samplers::RateLimiting.new \
36 | 1.0, rng: rng, time_class: time_class
37 | sampler.call.must_equal false
38 | end
39 |
40 | it "keeps track of last time" do
41 | rng = TestRandom.new [0.1, 0.3]
42 | time_class = TestTimeClass.new [start_time, time_200ms, time_400ms]
43 | sampler = OpenCensus::Trace::Samplers::RateLimiting.new \
44 | 1.0, rng: rng, time_class: time_class
45 | sampler.call.must_equal true
46 | sampler.call.must_equal false
47 | end
48 |
49 | it "returns true if span context was sampled" do
50 | rng = TestRandom.new [0.3]
51 | time_class = TestTimeClass.new [start_time, time_200ms]
52 | sampler = OpenCensus::Trace::Samplers::RateLimiting.new \
53 | 1.0, rng: rng, time_class: time_class
54 | trace_context = OpenCensus::Trace::TraceContextData.new "1", "2", 1
55 | span_context = OpenCensus::Trace::SpanContext.create_root \
56 | trace_context: trace_context
57 | sampler.call(span_context: span_context).must_equal true
58 | end
59 | end
60 | end
61 |
--------------------------------------------------------------------------------
/lib/opencensus/tags/config.rb:
--------------------------------------------------------------------------------
1 | # Copyright 2017 OpenCensus Authors
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | require "opencensus/config"
17 | require "opencensus/tags/formatters"
18 |
19 | module OpenCensus
20 | module Tags
21 | # Schema of the Tags configuration. See Tags#configure for more info.
22 | @config = Common::Config.new do |config|
23 | default_formatter = Formatters::Binary.new
24 | config.add_option! :binary_formatter, default_formatter do |value|
25 | value.respond_to?(:serialize) && value.respond_to?(:deserialize)
26 | end
27 | end
28 |
29 | # Expose the tags config as a subconfig under the main config.
30 | OpenCensus.configure do |config|
31 | config.add_alias! :tags, config: @config
32 | end
33 |
34 | class << self
35 | ##
36 | # Configure OpenCensus Tags. These configuration fields include
37 | # parameters formatter.
38 | #
39 | # This configuration is also available as the `tags` subconfig under the
40 | # main configuration `OpenCensus.configure`. If the OpenCensus Railtie is
41 | # installed in a Rails application, the configuration object is also
42 | # exposed as `config.opencensus.tags`.
43 | #
44 | # Generally, you should configure this once at process initialization,
45 | # but it can be modified at any time.
46 | #
47 | # Supported fields are:
48 | #
49 | # * `binary_formatter` The tags context propagation formatter to use.
50 | # Must be a formatter, an object with `serialize`, `deserialize`,
51 | # methods. See {OpenCensus::Tags::Formatters::Binary}.
52 | #
53 | # @example
54 | #
55 | # OpenCensus::Tags.configure do |config|
56 | # config.binary_formatter = OpenCensus::Tags::Formatters::Binary.new
57 | # end
58 | #
59 | def configure
60 | if block_given?
61 | yield @config
62 | else
63 | @config
64 | end
65 | end
66 |
67 | ##
68 | # Get the current configuration
69 | # @private
70 | #
71 | attr_reader :config
72 | end
73 | end
74 | end
75 |
--------------------------------------------------------------------------------
/docs/_layouts/default.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | {% seo %}
8 |
9 |
10 |
11 |
14 |
15 |
16 |