Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Fix SDK observable instruments to emit SDK Measurement #2501

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 5, 2022

Conversation

aabmass
Copy link
Member

@aabmass aabmass commented Mar 4, 2022

Description

The metrics SDK was not previously working for async instruments. The callbacks need to emit Measurements which can be consumed by MeasurementConsumer. This fixes it.

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)

How Has This Been Tested?

Updated tests and manually tested with this script

import time
from rich.pretty import pprint
from typing import Iterable
from opentelemetry._metrics.measurement import Measurement
from opentelemetry.sdk._metrics import MeterProvider
from opentelemetry.sdk._metrics.metric_reader import MetricReader
from opentelemetry.sdk._metrics.point import AggregationTemporality, Metric


class MyReader(MetricReader):
    def _receive_metrics(self, metrics: Iterable[Metric]) -> None:
        """Called by `MetricReader.collect` when it receives a batch of metrics"""
        pprint(metrics)

    def shutdown(self) -> bool:
        print("shutdown called")
        return True


def cpu_time_callback() -> Iterable[Measurement]:
    with open("/proc/stat") as procstat:
        procstat.readline()  # skip the first line
        for line in procstat:
            if not line.startswith("cpu"):
                break
            cpu, *states = line.split()
            yield Measurement(
                int(states[0]) // 100, {"cpu": cpu, "state": "user"}
            )
            yield Measurement(
                int(states[1]) // 100, {"cpu": cpu, "state": "nice"}
            )
            # ... other states


def main() -> None:
    reader = MyReader(preferred_temporality=AggregationTemporality.CUMULATIVE)
    mp = MeterProvider(metric_readers=[reader])
    meter = mp.get_meter("hellometer")
    mycounter = meter.create_counter("mycounter")
    meter.create_observable_counter(
        "system.cpu.time",
        callback=cpu_time_callback,
        unit="ms",
        description="System's CPU time",
    )
    for _ in range(20):
        mycounter.add(12, {"path": "/hello"})
        mycounter.add(10, {"path": "/world"})

    reader.collect()

    time.sleep(2)
    mp.shutdown()


if __name__ == "__main__":
    main()

The output is: https://gist.github.com/aabmass/d61350cdffe6f112401d2616eb41f866

Does This PR Require a Contrib Repo Change?

  • No.

Checklist:

  • Followed the style guidelines of this project
  • Unit tests have been added

@aabmass aabmass requested a review from a team March 4, 2022 17:35
@aabmass aabmass added metrics sdk Affects the SDK package. labels Mar 4, 2022
@aabmass aabmass force-pushed the fix-sdk-async-instruments branch from 87aaeae to 212f27c Compare March 4, 2022 17:45
Copy link
Contributor

@lzchen lzchen left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some great test cases!

@codeboten codeboten added the Skip Changelog PRs that do not require a CHANGELOG.md entry label Mar 4, 2022
@aabmass aabmass added the PR:please merge This PR is ready to be merged by a Maintainer (has enough valid approvals, successful build, etc.) label Mar 4, 2022
@lzchen lzchen merged commit 6fc9e4c into open-telemetry:main Mar 5, 2022
@aabmass aabmass deleted the fix-sdk-async-instruments branch March 5, 2022 19:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
metrics PR:please merge This PR is ready to be merged by a Maintainer (has enough valid approvals, successful build, etc.) sdk Affects the SDK package. Skip Changelog PRs that do not require a CHANGELOG.md entry
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants